Skip to content
Prev 65707 / 398506 Next

R: LIST function and LOOPS

You will need to capture the value of ss at the end of each 'i' as such

z4 <-function(w){

  output <- numeric(w)
  
  for (i in 1:w){
    
    set.seed(i+6)  # this is redundant line
    ss<-0
    
    for (j in 1:5){
      set.seed(j+1+(i-1)*6)
      r<-rnorm(1)
      ss<-ss+r
    }

    output[i] <- ss
  }
  return(output)
}

BTW, I do not think it is a good idea to set.seed() so many times.


To answer you more general question, see if the following is useful.
I am trying to simulate 'n' values from a standard normal distribution
but 'n' is random variable itself.

f <-function(w, lambda=3){
 
  tmp <- list(NULL)
  
  for (i in 1:w){
    n <- 1 + rpois(1, lambda=lambda)  # number of simulation required
    tmp[[ i ]]  <- rnorm(n)
  }

  # flatten the list into a ragged matrix
  out.lengths   <- sapply(tmp, length)
  out           <- matrix( nr=w, nc=max( out.lengths ) )
  rownames(out) <- paste("w =", 1:w)
  for(i in 1:w) out[i, 1:out.lengths[i] ] <- tmp[[i]]

  return(out)
}

f(6, lambda=3)

It is not very elegant but I hope that helps you out somehow.

Regards, Adai
On Thu, 2005-03-10 at 10:16 +0200, Clark Allan wrote: