【发布时间】:2020-11-30 12:23:24
【问题描述】:
这是一个测试 DF:
test_df <- structure(list(plant_sp = c("plant_1", "plant_1", "plant_2", "plant_2", "plant_3",
"plant_3", "plant_3", "plant_3", "plant_3", "plant_4",
"plant_4", "plant_4", "plant_4", "plant_4", "plant_4",
"plant_5", "plant_5", "plant_5", "plant_5", "plant_5"),
site = c("a", "a", "a", "a", "a",
"b", "b", "b", "b", "b",
"a", "a", "a", "a", "a",
"b", "b", "b", "b", "b"),
sp_rich = c(5, 3, 5, 3, 5,
7, 8, 8, 8, 10,
1, 4, 5, 6, 3,
7, 3, 12, 12,11)),
row.names = c(NA, -20L), class = "data.frame",
.Names = c("plant_sp", "site", "sp_rich"))
如果组中的行数大于 3,我想 group_by plant_sp 并提取 3 个随机行。
换句话说:取每个组,如果组大小大于 3,则在该组中随机只保留 3 行。
我正在尝试使用 if_else 但我无法做到这一点:
test_df <- test_df %>% group_by(plant_sp) %>%
if_else(length(plant_sp) > 3, sample_n(size =3))
我猜我没有正确使用 length() 函数。
你能帮帮我吗?
谢谢,伊多
【问题讨论】: