我通过以下方式制作了一个数据表:
p1 <- list(N=999)
d = data.table(ID = 1:p1$N)
d[,Initial_Grouping := (1:.N - 1) %/% 333]
所以我得到“ ID 1:333”,“ Initial_Grouping” = 0; “ ID 334:667”,“ Initial_Grouping” = 1; ID 667:999“,” Initial_Grouping“ = 2
现在,我想使用rnorm
函数并形成第三列“ Size”,其中包含每个“ Initial_Grouping”的随机变量。我希望每个组都有不同且特定的均值和标准差。
我尝试过的一件事是:
d[,Firm_Size := as.integer(exp((rnorm(333,mean=3,sd=1,by = (d$Initial_Grouping ==0))))),
as.integer(exp((rnorm(333,mean=3,sd=1,by = (d$Initial_Grouping ==1))))),
as.integer(exp((rnorm(333,mean=3,sd=1,by = (d$Initial_Grouping ==2)))))]
# Error in `[.data.table`(d, , `:=`(Size, as.integer(exp((rnorm(333, :
# Provide either by= or keyby= but not both
答案 0 :(得分:1)
使用您的参数定义查找data.table
:
z <- data.table(Initial_Grouping = c(0, 1, 2), mn = c(1, 5, 8), sd = c(1, 2, 9)))
setkey(z, "Initial_Grouping")
d[, rnorm(.N, mean = z[.BY, mn], sd = z[.BY, mn]), by = Initial_Grouping]
Initial_Grouping V1
1: 0 2.2026478
2: 0 -0.8718570
3: 0 2.5910559
4: 0 1.7419309
5: 0 1.5093134
---
995: 2 19.2724841
996: 2 24.4791871
997: 2 4.5289828
998: 2 6.4106569
999: 2 -0.7529038