【发布时间】:2021-12-08 14:33:28
【问题描述】:
我有一个具有这种结构的数据框:
> df
factor y x
1 2 0
1 3 0
1 1 0
1 2 0
2 3 0
2 1 0
2 3 1
3 4 1
3 3 1
3 6 3
3 5 2
4 4 1
4 7 8
4 2 1
2 5 3
在实际数据集中,我有 200 行和不同的变量:几个连续变量和一个因子变量,有 70 个级别,每个级别最多 4 个观察值。
我想将我的整个数据帧随机分成 4 个大小相等的组,而无需在每个组内仅在因子变量中进行替换。换句话说,我希望因子变量的每个级别每组不超过一次。
我尝试了不同的解决方案。 例如,我尝试将“因子”变量分成四组而不进行替换,如下所示:
factor1 <- as.character(df$factor)
set.seed(123)
group1 <- sample(factor, 35,replace = FALSE)
factor2 <- setdiff(factor1, group1)
group2 <- sample(factor2, 35,replace = FALSE)
# and the same for "group3" and "group4"
但是我不知道如何将组向量(group1、group2 等)与我的 df 中的其他变量('x' 和 'y')相关联。
我也试过:
group1 <- sample_n(df, 35, replace = FALSE)
但是这个解决方案也失败了,因为我的数据框不包含重复的行。唯一重复的值在因子变量中。
最后,我尝试使用在回答类似问题here时提出的解决方案,适应我的情况:
random.groups <- function(n.items = 200L, n.groups = 4L,
factor = rep(1L, n.items)) {
splitted.items <- split(seq.int(n.items), factor)
shuffled <- lapply(splitted.items, sample)
1L + (order(unlist(shuffled)) %% n.groups)
}
df$groups <- random.groups(nrow(df), n.groups = 4)
但是,生成的 4 组包含重复的因子变量值,因此某些东西无法正常工作。
我非常感谢任何解决此问题的想法或建议!
【问题讨论】:
-
使用 dplyr() : new_df % group_by(factor) %>% sample_n(35)。请提供示例输出以了解更多详细信息。