我有一个超过 20k 行的数据框。如下是我的数据框的示例:
df <- data.frame(
ID = c("1234", "edje", "hgt1", "4567", "0900", "wwwl", "yyyt", "5789", "hlkk", "3333"),
group = c("V1", "V1", "V2", "V2", "V2", "V3", "V3", "UN", "UN", "UN")
)
Run Code Online (Sandbox Code Playgroud)
现在我想将此数据帧拆分为 10 个数据帧,或多或少具有相似数量的行,然后我想将具有相同值的行放在同一数据帧的组列中,除了那些显示“UN”的行在组列中,因为这些行应该随机分布在所有 10 个数据帧中。
我想要这样的东西:
df1 <- data.frame(
ID = c("1234", "edje", "5789"),
group = c("V1", "V1", "UN")
)
df2 <- data.frame(
ID = c("hgt1", "4567", "0900", "hlkk"),
group = c("V2", "V2", "V2", "UN")
)
df3 <- data.frame(
ID = c("wwwl", "yyyt", "3333"),
group = c("V3", "V3", "UN")
)
Run Code Online (Sandbox Code Playgroud)
但就我而言,我想将 df 分为 10 个数据帧。我怎样才能在R中执行此操作?
在这里,我首先制作一个允许的非“联合国”团体的向量。然后我进行一个新的分组,其中“UN”行被随机分配其中之一,然后按该新分组进行拆分。
library(dplyr)
grps <- unique(df$group)
grps <- grps[grps != "UN"]
df %>%
mutate(group2 = if_else(group == "UN",
sample(grps, nrow(df), replace = TRUE),
group)) %>%
split(.$group2)
Run Code Online (Sandbox Code Playgroud)
EDIT-OP 指定他们的实际问题有超过 4000 个组,他们希望将其分成 10 个类似大小的数据帧。这是一个替代示例,其中有 26 个大小截然不同的组(加上一些重新分配的“UN”),我们将其分为 10 个大小相似的组。
df <- data.frame(
ID = ids::adjective_animal(n = 400),
group = sample(c(letters, "UN"), 400, replace = TRUE, prob = 27:1)
)
Run Code Online (Sandbox Code Playgroud)
然后我们可以执行与上面相同的步骤,但也将 26 个组分配到 10 个 bin 中:
grps <- unique(df$group)
grps <- grps[grps != "UN"]
df2 <- df %>%
mutate(group2 = if_else(group == "UN",
sample(grps, nrow(df), replace = TRUE),
group))
counts <- count(df2, group2)
df3 <- df2 |>
left_join(counts |>
bind_cols(bin = adagio::bpp_approx(counts$n, cap = 42)$xbins))
Run Code Online (Sandbox Code Playgroud)
只是为了检查一下,尽管我们有 26 组大小差异很大的垃圾箱,但这些垃圾箱的大小相似。
count(df3, bin)
bin n
1 1 42
2 2 42
3 3 42
4 4 41
5 5 39
6 6 42
7 7 40
8 8 40
9 9 39
10 10 33
Run Code Online (Sandbox Code Playgroud)