[英]Apply a function to variables with a name pattern for each id with NA values
我有一個數據表,我想在其中計算每個 id 以“金額”開頭的變量組的平均值。
以數量開頭的變量數量可能會有所不同,但在我的真實數據中它們遠遠超過 100(並且一些變量具有 NA 值)。
id variable amountA amountB amountC amountD
1 A 8 7 6 2
2 B 6 2 1 2
3 C 6 6 9 4
4 D 1 6 2 7
在我的數據中,我嘗試失敗:
DT[,testvar := apply(DT[ ,grepl("amount",names(DT))],1,mean)]
DT[,testvar := mean(DT[ ,grepl("amount",names(DT))],na.rm=TRUE), by = idvar]
我正在嘗試使用 .EACHI 解決它,但我還沒有弄清楚。 任何想法或評論都非常感謝。
示例表:
structure(list(id = 1:4, variable = structure(1:4, .Label = c("A",
"B", "C", "D"), class = "factor"), amountA = c(8L, 6L, 6L, 1L
), amountB = c(7L, 2L, 6L, 6L), amountC = c(6L, 1L, 9L, 2L),
amountD = c(2L, 2L, 4L, 7L)), .Names = c("id", "variable",
"amountA", "amountB", "amountC", "amountD"), class = "data.frame", row.names = c(NA,
-4L))
這是一個可能的解決方案,采用了 Arun 的一些建議:
DT[, testvar:=rowMeans(.SD, na.rm=T), .SDcols=grep("^amount", names(DT), value=T)]
產生:
id variable amountA amountB amountC amountD testvar
1: 1 A 8 7 6 2 5.75
2: 2 B 6 2 1 2 2.75
3: 3 C 6 6 9 4 6.25
4: 4 D 1 6 2 7 4.00
我們用.SDcols
和grep
定義我們想要成為內部.SD
對象的一部分的列,然后我們只是rowSums
結果.SD
。
在最新版本的data.table
您可以通過使用.SDcols
patterns
來快捷方式:
DT[, testvar := rowMeans(.SD, na.rm = TRUE), .SDcols = patterns('amount')]
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.