在另一列中的条件上采样

时间:2019-02-27 04:33:41

标签: r random

如何随机采样2个权重在0.5-1.0之间的报告

也;如何从权重为0.5-1.0的报告中随机抽取20%

DF <- data.frame(Report_ID=c(2,8,12,15,16, 51,67,89,88,98),
                        Weight=c(0.05,0.1,0.25,0.30,0.35,0.56,0.75,0.81,0.95,1.0))

2 个答案:

答案 0 :(得分:1)

使用dplyr

library(dplyr)

示例2报告:

DF %>% 
  filter(between(Weight, 0.5, 1)) %>% 
  sample_n(2)

抽样20%的报告:

DF %>% 
  filter(between(Weight, 0.5, 1)) %>% 
  sample_frac(0.5)

答案 1 :(得分:1)

您可以尝试以下方法:

rand_sample <- DF[ sample( which(DF$Weight > 0.4 & DF$Weight < 1.1), round(0.2*length(which(DF$Weight > 0.4 & DF$Weight < 1.1)))), ]