使用下面的这个非常简单的数据示例,我的目标是对A
的所有3个样本进行抽样,而对B
的7个样本中的5个抽样。
id group
1 A
2 A
3 A
4 B
5 B
6 B
7 B
8 B
9 B
10 B
ex_df <- data.frame(id = 1:10, group = c(rep("A", 3), rep("B", 7)))
现在,通常只是使用sample_n
中的dplyr
的情况,这样代码将遵循
sel_5 <- ex_df %>%
group_by(group) %>%
sample_n(5)
除了这会导致错误(出于明显的原因)
错误:
size
必须小于或等于2(数据大小),已设置replace
= TRUE,可使用替换抽样
,但无法进行抽样替换。有什么方法可以将sample_n
的大小设置为最小5或组的大小?
或者也许我不知道的另一个功能能够做到这一点?
答案 0 :(得分:1)
我遇到了同样的问题,这就是我所做的。
library(dplyr)
split_up <- split(ex_df, f = ex_df$group)
#split original dataframe into a list of dataframes for each unique group
sel_5 <- lapply(split_up, function(x) {x %>% sample_n(ifelse(nrow(x) < 5, nrow(x), 5))})
#on each dataframe, subsample to 5 or to the number of rows if there are less than 5
sel_5 <- do.call("rbind", sel_5)
#bind it back up!