# [R] R help on loops

Berend Hasselman bhh at xs4all.nl
Fri Jun 7 11:24:36 CEST 2013

```On 07-06-2013, at 10:59, Laz <lmramba at ufl.edu> wrote:

> Dear R users,
>
> I am stuck here: My first function returns a vector of 5 values.
> In my second function, I want to repeat this, a number of times, say 10
> so that I have 10 rows and five columns but I keep on getting errors.
>
> See the code and results below:
>
> optm <-function(perm, verbose = FALSE)
> {
>   trace<-c()
>   for (k in 1:perm){
> trace[k]<-Rspatswap(rhox=0.6,rhoy=0.6,sigmasqG=0.081,SsqR=1)[1]
>     perm[k]<-k
>     mat<-cbind(trace, perm = seq(perm))
>   }
>   if (verbose){
>     cat("***starting matrix\n")
>     print(mat)
>   }
>   # iterate till done
>   while(nrow(mat) > 1){
>     high <- diff(mat[, 'trace']) > 0
>     if (!any(high)) break  # done
>     # find which one to delete
>     delete <- which.max(high) + 1L
>     mat <- mat[-delete, ]
>     newmat<-apply(mat,2,mean)[1]
>     sdm<-sd(mat[,1])
>     sem<-sdm/sqrt(nrow(mat))
>     maxv<-mat[1,1]
>     minv<-mat[nrow(mat),1]
>       }
>   stats<-cbind(average=newmat,sd=sdm,se=sem,min=minv,max=maxv)
>   stats
> }
>
>> test<-optm(perm=20)
>> test
>         average           sd           se       min      max
> trace 0.8880286 0.0009178193 0.0004589096 0.8870152 0.889241
>
>
> itn<-function(it){
> siml<-matrix(NA,ncol=5,nrow=length(it))
>   for(g in 1:it){
>    siml[g]<-optm(perm=20)
>   }
> siml<-cbind(siml=siml)
> siml
> }
>
>> ans<-itn(5)
> Warning messages:
> 1: In siml[g] <- optm(perm = 20) :
>   number of items to replace is not a multiple of replacement length
> 2: In siml[g] <- optm(perm = 20) :
>   number of items to replace is not a multiple of replacement length
> 3: In siml[g] <- optm(perm = 20) :
>   number of items to replace is not a multiple of replacement length
> 4: In siml[g] <- optm(perm = 20) :
>   number of items to replace is not a multiple of replacement length
> 5: In siml[g] <- optm(perm = 20) :
>   number of items to replace is not a multiple of replacement length
>> ans
>           [,1]      [,2]      [,3]      [,4]      [,5]
> [1,] 0.8874234 0.8861666 0.8880521 0.8870958 0.8876469
>

1. Not reproducible code. Where does function Rspatswap come from?

2. You have several errors in function itn:
Argument it is a scalar: length(it) is 1. You need to do siml <- matrix(NA,ncol=5,nrow=it)
Next in the g-loop you want to fill row g so do: siml[g,] <- …..

Finally why are you doing siml <- cbind(siml=siml)?
Seems superfluous to me. Delete the line.

Berend

```