I have a following sample data, and I am trying to create random numbers by large number of groups, but it is taking too much time. I wonder whether there is an efficient way for this:
library(data.table)
d <- mtcars
n <- 10000
k1<-rbindlist(replicate(n, d, simplify = FALSE))
k1[,factor_var:=rep(seq(1,80000),4)] #sample data
#generating random number
k1[,rand:=runif(nrow(k1),0,1),factor_var]
You can use this command.
k1[, rand:=runif(.N, 0, 1), factor_var]
Using nrow is slow in the sense that R computes the number of rows each time. You should either use .N or compute nrow beforehand, like this
nr <- nrow(k1)
k1[, rand:=runif(nr, 0, 1), factor_var]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With