问题描述
我正在尝试以分组方式将采样函数应用于数据帧,在该数据帧中,应从每个组(如果组大小小于n 或所有组成员)中采样n个样本。
I am trying to apply a sampling function in a grouped fashion to a data frame, where it should sample n samples from each group, or all group members if the group size is smaller than n.
使用dplyr,我首先尝试
Using dplyr, I first tried
library(dplyr)
mtcars %>% group_by(cyl) %>% sample_n(2)
此当n小于所有组的大小时有效,但是当我选择大于组的大小n时不接受完整的组(请注意,一个圆柱组中有7辆车):
This works when n is smaller than all the group sizes but does not take the full group when I choose n larger than the group size (note that there are 7 cars in one of the cyl groups):
mtcars %>% group_by(cyl) %>% sample_n(8)
Error: `size` must be less or equal than 7 (size of data),
set `replace` = TRUE to use sampling with replacement
通过创建一个适应的group_n函数来解决此问题,例如:
I tried to solve this by creating an adapted group_n function like so:
sample_n_or_all <- function(tbl, n) {
if (nrow(tbl) < n)return(tbl)
sample_n(tbl, n)
}
但使用我的自定义函数( mtcars%>%group_by(cyl)% >%sample_n_or_all(8)
)会产生相同的错误。
but using my custom function (mtcars %>% group_by(cyl) %>% sample_n_or_all(8)
) generates the same error.
关于如何调整函数的任何建议,以便将其应用于每个函数组中的?还是该问题的另一种解决方案?
Any suggestions how I can adapt my function so I can apply it to each of the groups? Or another solution to the problem?
推荐答案
我们可以检查组中的行数并将值传递给 sample_n
。
We could check the number of rows in the group and pass the value to sample_n
accordingly.
library(dplyr)
n <- 8
temp <- mtcars %>% group_by(cyl) %>% sample_n(if(n() < n) n() else n)
temp
# mpg cyl disp hp drat wt qsec vs am gear carb
# <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl>
# 1 21.4 4 121 109 4.11 2.78 18.6 1 1 4 2
# 2 27.3 4 79 66 4.08 1.94 18.9 1 1 4 1
# 3 24.4 4 147. 62 3.69 3.19 20 1 0 4 2
# 4 22.8 4 108 93 3.85 2.32 18.6 1 1 4 1
# 5 26 4 120. 91 4.43 2.14 16.7 0 1 5 2
# 6 33.9 4 71.1 65 4.22 1.84 19.9 1 1 4 1
# 7 30.4 4 75.7 52 4.93 1.62 18.5 1 1 4 2
# 8 30.4 4 95.1 113 3.77 1.51 16.9 1 1 5 2
# 9 21 6 160 110 3.9 2.62 16.5 0 1 4 4
#10 17.8 6 168. 123 3.92 3.44 18.9 1 0 4 4
# … with 13 more rows
之后,我们可以检查每个组中的行数。
We can check number of rows in each group after that.
table(temp$cyl)
#4 6 8
#8 7 8
table(mtcars$cyl)
# 4 6 8
#11 7 14
这篇关于自定义分组的dplyr函数(sample_n)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!