[R] R help on loops
Berend Hasselman
bhh at xs4all.nl
Fri Jun 7 12:25:49 CEST 2013
On 07-06-2013, at 11:57, Laz <lmramba at ufl.edu> wrote:
> Dear Berend,
>
> I have made some changes but I still get errors:
>
> For reproducibility,
> Rspatswap() is a function which originally returns a single value. For example Rspatswap(...) and you get 0.8
>
> So, run Rspatswap() 20 times and store all the values.
> Then from these 20 values, calculate the calculate average, sd,se,min,max to get something similar to:
>
> average sd se min max
> trace 0.8880286 0.0009178193 0.0004589096 0.8870152 0.889241
>
> If we repeat the function 10 times, then I expect 10 rows with 5 columns but it does not work ?
>
Replacing Rspatswap(…)[1] with runif(1) (you could/should have done that to provide reproducible code) and the modifications I suggested you make in your function itn() like this
itn<-function(it){
siml<-matrix(NA,ncol=5,nrow=it)
for(g in 1:it){
siml[g,]<-optm(perm=20)
}
siml
}
running itn(10) I get a matrix with 10 rows and 5 columns.
So what do you mean by "it does not work"?
You sometimes get an error message from apply due to a bad dim() like this
Error in apply(mat, 2, mean) : dim(X) must have a positive length
When the result of mat[-delete,] is a matrix with a single row the result is simplified to a vector. See ?"[" in particular the drop argument.
So this should work in function optm()
mat <- mat[-delete,, drop=FALSE]
Berend
More information about the R-help
mailing list