[R] Simulation function

0 views
Skip to first unread message

MarcioRibeiro

unread,
Aug 18, 2009, 11:55:33 AM8/18/09
to r-h...@r-project.org

Hi listers,
I've been looking for a procedure, but I am not succeding...
I have a function that give multiple results...
Then, I would like to simulate this function n times, so I need to save/keep
the n multiple results, in order to calculate my desired statistics...
I have already tried with the RETURN and LIST FUNCTION, but I am not getting
it right...
An example of what I am looking for sounds like this...

boot<-function(a,b,c){
media<-(a+b+c)/3
var_app<-var(a)
list(media=media,var_app=var_app)
}
boot(2,4,10)

simul<-function(S){
results<-rep(0,S)
for(i in 1:S){
results[i]<-boot(2,4,10)
}
var<-var(media)
mean_var<-mean(var_app)
var_var<-var(var_app)
list(var=var,mean_var=mean_var,var_var=var_var)
}
simul(5)

--
View this message in context: http://www.nabble.com/Simulation-function-tp25027993p25027993.html
Sent from the R help mailing list archive at Nabble.com.

______________________________________________
R-h...@r-project.org mailing list
https://stat.ethz.ch/mailman/listinfo/r-help
PLEASE do read the posting guide http://www.R-project.org/posting-guide.html
and provide commented, minimal, self-contained, reproducible code.

jim holtman

unread,
Aug 18, 2009, 7:01:05 PM8/18/09
to MarcioRibeiro, r-h...@r-project.org
You need to store your results in a list and then access the
information in the list to get the values:

> boot<-function(a,b,c){
+ media<-(a+b+c)/3
+ var_app<-var(a)
+ list(media=media,var_app=var_app)
+ }
> boot(2,4,10)
$media
[1] 5.333333

$var_app
[1] NA

>
> simul<-function(S){
+ results<-list()
+ for(i in 1:S){
+ results[[i]]<-boot(2,4,10)
+ }
+ var<-var(sapply(results, '[[', 'media'))
+ mean_var<-mean(sapply(results, '[[', 'var_app'))
+ var_var<-var(sapply(results, '[[', 'var_app'))
+ list(var=var,mean_var=mean_var,var_var=var_var)
+ }
> simul(5)
$var
[1] 0

$mean_var
[1] NA

$var_var
[1] NA

>

--
Jim Holtman
Cincinnati, OH
+1 513 646 9390

What is the problem that you are trying to solve?

Reply all
Reply to author
Forward
0 new messages