这个问题是在组加权平均值的基础上提出的:我想使用
数据如下:
使用Roland在上述问题中提供的答案:
但是我接下来会得到:
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。
NB:我使用data.table包的1.9.3版本。
Error in as.double(w) : cannot coerce type 'closure' to vector of type 'double'
。 - PatrickTdt[, lapply(mget(colsToKeep), weighted.mean, w=weights), by=.(region,state,country)]。您的错误似乎表明您正在使用函数作为输入使用
as.double`(这与错误无关)。 - Arunas.list()
。我当时一定是写错了,因为mget()
当时不起作用(这是另一个 bug,但我们已经修复了)。 - Arun