[英]How to apply the function to each row?
我想通過隨機抽樣從現有變量total
生成 4 個新列。 每行的結果應滿足條件s1 + s2 + s3 + s4 == total
。 例如,
> tabulate(sample.int(4, 100, replace = TRUE))
[1] 22 21 27 30
以下代碼不起作用,因為該函數似乎回收第一行並按列應用它。
DT <- data.table(total = c(100, 110, 90, 92))
DT[, c(paste0("s", 1:4)) := tabulate(sample.int(4, total, replace = TRUE))]
> DT
total s1 s2 s3 s4
1: 100 31 31 31 31
2: 110 25 25 25 25
3: 90 22 22 22 22
4: 92 22 22 22 22
如何解決這個問題? 我顯然缺少對R
向量/列表如何工作的一些基本理解。 您的幫助將不勝感激。
編輯了以下已編輯的問題:
當您想要分配給許多列時, data.table
將在內部期望一個列表。 為了讓每一行都是獨一無二的,你可以by
每一行添加一個來做到這一點:
DT <- data.table(total = c(100, 110, 90, 102, 92))
DT[, c(paste0("s", 1:4)) := {
as.list(tabulate(sample.int(4, total, replace = TRUE)))
}, by = seq(NROW(DT))]
輸出以下內容,滿足 OP 標准:
> DT
total s1 s2 s3 s4
1: 100 27 28 28 17
2: 110 25 23 36 26
3: 90 26 19 26 19
4: 102 28 24 21 29
5: 92 17 27 22 26
> apply(DT[, 2:5],1, sum)
[1] 100 110 90 102 92
也許你可以試試下面的代碼
DTout <- cbind(
DT,
do.call(
rbind,
lapply(DT$total, function(x) diff(sort(c(0, sample(x - 1, 3), x))))
)
)
這使
total V1 V2 V3 V4
1: 100 51 5 17 27
2: 110 41 1 40 28
3: 90 32 34 14 10
4: 102 5 73 13 11
5: 92 17 13 17 45
測試
> rowSums(DTout[,-1])
[1] 100 110 90 102 92
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.