can lapply not modify variables in a higher scope
Posted
by stevejb
on Stack Overflow
See other posts from Stack Overflow
or by stevejb
Published on 2010-04-17T00:48:39Z
Indexed on
2010/04/17
0:53 UTC
Read the original article
Hit count: 321
I often want to do essentially the following:
mat <- matrix(0,nrow=10,ncol=1)
lapply(1:10, function(i) { mat[i,] <- rnorm(1,mean=i)})
But, I would expect that mat would have 10 random numbers in it, but rather it has 0. (I am not worried about the rnorm part. Clearly there is a right way to do that. I am worry about affecting mat from within an anonymous function of lapply) Can I not affect matrix mat from inside lapply? Why not? Is there a scoping rule of R that is blocking this?
© Stack Overflow or respective owner