【发布时间】:2020-02-12 04:47:25
【问题描述】:
我想有效地从data.table 中按组进行随机抽样,但应该可以为每组抽样不同的比例。
如果我想从每个组中抽取sampling_fraction 的分数,我可以从this 问题和related 答案中得到启发来做类似的事情:
DT = data.table(a = sample(1:2), b = sample(1:1000,20))
group_sampler <- function(data, group_col, sample_fraction){
# this function samples sample_fraction <0,1> from each group in the data.table
# inputs:
# data - data.table
# group_col - column(s) used to group by
# sample_fraction - a value between 0 and 1 indicating what % of each group should be sampled
data[,.SD[sample(.N, ceiling(.N*sample_fraction))],by = eval(group_col)]
}
# what % of data should be sampled
sampling_fraction = 0.5
# perform the sampling
sampled_dt <- group_sampler(DT, 'a', sampling_fraction)
但是,如果我想从第 1 组中抽取 10%,从第 2 组中抽取 50%,该怎么办?
【问题讨论】:
-
你如何定义哪个是第 1 组,哪个是第 2 组
-
在上面的例子中,列 'a' 的值是 1 和 2。因此,组 a 和组 2。我认为为了确保为每个组分配正确的采样分数,它可能可以在函数的输入中使用命名向量或类似的东西。我只是不确定该怎么做
标签: r data.table oversampling