【发布时间】:2019-05-09 13:16:16
【问题描述】:
我有以下数据结构:
set.seed(100)
x <- data.frame("smp_1"=runif(20)*100,"smp_2"=runif(20)*99)
x["weight_1"] = x$smp_1/sum(x$smp_1)
x["weight_2"] = x$smp_2/sum(x$smp_2)
> head(x)
smp_1 smp_2 weight_1 weight_2
1 66.61718 68.976341 0.05721288 0.061115678
2 24.65804 77.966842 0.02117709 0.069081607
3 66.10397 1.611913 0.05677212 0.001428216
4 93.95866 1.793973 0.08069459 0.001589529
5 19.96638 31.008240 0.01714774 0.027474488
6 66.35187 97.033923 0.05698502 0.085975770
现在我想创建一个新的数据框,该数据框使用权重列作为概率从每个 smp 列中采样,并将每个列样本添加到新数据框和新列中。我可以使用 for 循环来做到这一点:
tempdf <- data.frame(matrix(0,ncol=0,nrow=1000))
for (k in 1:2){
tempdf[,paste0("sim_",k)] <- sample(x[,paste0("smp_",k)],size=1000, replace=T, prob = x[,paste0("weight_",k)])
}
我的问题是如何以更有效的方式在没有 for 循环的情况下做到这一点?我将采样 100k 的多列,所以我需要一些非常快的东西。
【问题讨论】:
标签: r