我正在尝试结合两种方法:
- 以可扩展的方式引导 data.table 中的多个列 https://stackoverflow.com/questions/38989932/bootstrapping-multiple-columns-in-data-table-in-a-scalable-fashion-r
with
- R 中的 Bootstrap 加权平均值 https://stackoverflow.com/questions/46231261/bootstrap-weighted-mean-in-r
这是一些随机数据:
## Generate sample data
# Function to randomly generate weights
set.seed(7)
rtnorm <- function(n, mean, sd, a = -Inf, b = Inf){
qnorm(runif(n, pnorm(a, mean, sd), pnorm(b, mean, sd)), mean, sd)
}
# Generate variables
nps <- round(runif(3500, min=-1, max=1), 0) # nps value which takes 1, 0 or -1
group <- sample(letters[1:11], 3500, TRUE) # groups
weight <- rtnorm(n=3500, mean=1, sd=1, a=0.04, b=16) # weights between 0.04 and 16
# Build data frame
df = data.frame(group, nps, weight)
# The following packages / libraries are required:
require("data.table")
require("boot")
这是上面第一篇文章中增强加权平均值的代码:
samplewmean <- function(d, i, j) {
d <- d[i, ]
w <- j[i, ]
return(weighted.mean(d, w))
}
results_qsec <- boot(data= df[, 2, drop = FALSE],
statistic = samplewmean,
R=10000,
j = df[, 3 , drop = FALSE])
这完全没问题。
下面是上面第二篇文章中的代码,通过数据表中的组引导平均值:
dt = data.table(df)
stat <- function(x, i) {x[i, (m=mean(nps))]}
dt[, list(list(boot(.SD, stat, R = 100))), by = group]$V1
这也很好用。
我很难结合这两种方法:
跑步 …
dt[, list(list(boot(.SD, samplewmean, R = 5000, j = dt[, 3 , drop = FALSE]))), by = group]$V1
... 出现错误消息:
Error in weighted.mean.default(d, w) :
'x' and 'w' must have the same length
跑步 …
dt[, list(list(boot(dt[, 2 , drop = FALSE], samplewmean, R = 5000, j = dt[, 3 , drop = FALSE]))), by = group]$V1
…引发了一个不同的错误:
Error in weighted.mean.default(d, w) :
(list) object cannot be coerced to type 'double'
我仍然无法理解 data.table 中的参数以及如何组合运行 data.table 的函数。
我将不胜感激任何帮助。