Based on given averages and standard deviations, I'm trying to fill columns with various sample runs. What I have right now is:
A = data.table(ave = c(20, 3), std = c(.1, 1))
A[, paste0("scenario", c(1:3)) := rnorm(2, ave, std)]
Which results in the table:
ave std scenario1 scenario2 scenario3
20 0.1 20.2377 20.2377 20.2377
3 1.0 2.6497 2.6497 2.6497
So clearly, its running rnorm on one vector, then repeating that same vector for each column. How do I make it recalculate each column? I've tried things like
matrix(rnorm(6, ave, std), 2, 3)
or using transpose(lapply(...))
but neither seems to work.
您可以为每列调用rnorm
:
A[, paste0("scenario", c(1:3)) := lapply(1:3, function(x) rnorm(2, ave, std))]
我们可以使用replicate
A[, paste0("scenario",c(1:3)) := replicate(3, rnorm(2, ave, std), simplify = FALSE)]
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.