【发布时间】:2014-09-24 14:22:27
【问题描述】:
这个问题跟在group weighted means 上的另一个问题有关:我想使用data.table 创建加权组内平均值。与最初的问题不同的是,要平均的变量的名称是在一个字符串向量中指定的。
数据:
df <- read.table(text= "
region state county weights y1980 y1990 y2000
1 1 1 10 100 200 50
1 1 2 5 50 100 200
1 1 3 120 1000 500 250
1 1 4 2 25 100 400
1 1 4 15 125 150 200
2 2 1 1 10 50 150
2 2 2 10 10 10 200
2 2 2 40 40 100 30
2 2 3 20 100 100 10
", header=TRUE, na.strings=NA)
使用 Roland 对上述问题的建议答案:
library(data.table)
dt <- as.data.table(df)
dt2 <- dt[,lapply(.SD,weighted.mean,w=weights),by=list(region,state,county)]
我有一个带有字符串的向量,用于动态确定我想要组内加权平均值的列。
colsToKeep = c("y1980","y1990")
但我不知道如何将它作为 data.table 魔术的参数传递。
我试过了
dt[,lapply(
as.list(colsToKeep),weighted.mean,w=weights),
by=list(region,state,county)]`
但我得到:
Error in x * w : non-numeric argument to binary operator
不知道如何实现我想要的。
额外问题:我希望保留原始列名,而不是获取 V1 和 V2。
注意,我使用的是 1.9.3 版的 data.table 包。
【问题讨论】:
标签: r data.table