在R语言中,可以使用dplyr包和sample_n函数进行解决。
首先,需要将数据按组进行分组,然后在组内进行随机抽样,直到达到组总和为止。以下是实现的代码示例:
library(dplyr)
df <- data.frame(
group = c(1, 1, 1, 2, 2, 2),
value = c(10, 20, 30, 5, 10, 15)
)
res <- df %>%
group_by(group) %>%
do(sample_n(.,
size = which.max(cumsum(.$value) >= sum(.$value) / 2),
replace = FALSE))
以上代码将数据集df
按组分组,并使用sample_n
函数在每个组内进行随机抽样,直到达到组总和的一半为止。最后,结果保存在res
变量中。
注意,由于这是一种随机抽样方法,因此结果在每次运行时可能会略有不同。
下一篇:按组随机排序行”