R 重复取样并更换,直到超过阈值
我有一个包含两个变量的数据集:一个ID和一个amount。我想对记录进行采样(替换),直到采样的金额之和超过原始金额之和 我有可以工作的示例代码,但是有更好的方法吗?我希望最终在一个大数据集上运行100K次迭代,而我的方法似乎很笨拙 在下面的代码中,我只运行了3次迭代R 重复取样并更换,直到超过阈值,r,sampling,R,Sampling,我有一个包含两个变量的数据集:一个ID和一个amount。我想对记录进行采样(替换),直到采样的金额之和超过原始金额之和 我有可以工作的示例代码,但是有更好的方法吗?我希望最终在一个大数据集上运行100K次迭代,而我的方法似乎很笨拙 在下面的代码中,我只运行了3次迭代 set.seed(7777) df <- data.frame(ID = seq(1,5), AMT = sample(1:100, 5, replace = T)) threshold
set.seed(7777)
df <- data.frame(ID = seq(1,5),
AMT = sample(1:100, 5, replace = T))
threshold <- sum(df$AMT)
output <- NULL
for (i in 1:3) {
repeat{
sel <- df[sample(nrow(df), size = 1),]
sel <- cbind(iter=i, sel)
output <- rbind(output,
sel)
check_sum <- subset(output, iter == i)
if(sum(check_sum$AMT) > threshold) break
}
}
set.seed(7777)
df可以使用递归(调用自身的函数)。此外,您不需要存储所有采样结果(这里我们只存储行号)
对于rbindlist()
函数,似乎需要重叠一个数字向量
set.seed(7777)
df <- data.frame(ID = 1:5,AMT = sample(1:100, 5, TRUE))
threshold <- sum(df$AMT)
# Specify N not to call it multiple times
N <- nrow(df)
repeatUntilSum <- function(input = NULL) {
# Sample one row number and join with input
result <- c(sample(N, 1), input)
# Check if still too low
if (sum(df$AMT[result]) <= threshold) {
# Run function again
repeatUntilSum(result)
} else {
# Return full sampled result
return(df[result, ])
}
}
data.table::rbindlist(lapply(1:3, repeatUntilSum), idcol = "iter")