One of the main advantages of higher-order functions like lapply()
or sapply()
is that you don't have to initialize your "container" (matrix in this case).
As Fojtasek suggests:
as.matrix(lapply(1:10,function(i) rnorm(1,mean=i)))
Alternatively:
do.call(rbind,lapply(1:10,function(i) rnorm(1,mean=i)))
Or, simply as a numeric vector:
sapply(1:10,function(i) rnorm(1,mean=i))
If you really want to modify a variable above of the scope of your anonymous function (random number generator in this instance), use <<-
> mat <- matrix(0,nrow=10,ncol=1)
> invisible(lapply(1:10, function(i) { mat[i,] <<- rnorm(1,mean=i)}))
> mat
[,1]
[1,] 1.6780866
[2,] 0.8591515
[3,] 2.2693493
[4,] 2.6093988
[5,] 6.6216346
[6,] 5.3469690
[7,] 7.3558518
[8,] 8.3354715
[9,] 9.5993111
[10,] 7.7545249
See this post about <<-
. But in this particular example, a for-loop would just make more sense:
mat <- matrix(0,nrow=10,ncol=1)
for( i in 1:10 ) mat[i,] <- rnorm(1,mean=i)
with the minor cost of creating a indexing variable, i
, in the global workspace.