Yes, you essentially change the pre , which is local to the anonymous function, which itself will return the result of the last estimate (vector of length 1), therefore sapply() returns the correct solution as a vector (because it accumulates individual lengths of 1 vector), but it does not change pre in the global workspace.
You can get around this using the <<- operator:
set.seed(1) count <- 5 pre <- numeric(count) sapply(1:count, function(i) { pre[i] <<- rnorm(1) }) > pre [1] -0.6264538 0.1836433 -0.8356286 1.5952808 0.3295078
What has changed pre , but I would not do it for various reasons.
In this case, I donβt think that much can be learned from the pre-allocation of pre in the case of sapply() .
Also, for this example, both are terribly ineffective; just get rnorm() to generate random count numbers. But I think this example was just to illustrate the point?
source share