使用 dplyr 从数据框中采样子组行 [英] sample rows of subgroups from dataframe with dplyr
问题描述
如果我想从不同的组中随机选择一些样本,我使用 plyr 包和下面的代码
If I want to randomly select some samples from different groups I use the plyr package and the code below
require(plyr)
sampleGroup<-function(df,size) {
df[sample(nrow(df),size=size),]
}
iris.sample<-ddply(iris,.(Species),function(df) sampleGroup(df,10))
这里从每个物种中选择了 10 个样本.
Here 10 samples are selected from each species.
我的一些数据框非常大,我的问题是我可以在 dplyr 包中使用相同的 sampleGroup 函数吗?或者在 dplyr 中还有另一种方法可以做同样的事情吗?
Some of my dataframes are very big and my question is can I use the same sampleGroup function with the dplyr package? Or is there another way to do the same in dplyr?
编辑
dplyr 包的 0.2 版引入了两个新函数来从表 sample_n 和 sample_frac 中选择随机行
Version 0.2 of the dplyr package introduced two new functions to select random rows from a table sample_n and sample_frac
推荐答案
是的,您可以通过函数 do() 优雅地使用 dplyr.下面是一个例子:
Yes, you can use dplyr elegantly by the function do(). Here is an example:
mtcars %>%
group_by(cyl) %>%
do(sample_n(.,2))
结果是这样的
Source: local data frame [6 x 11]
Groups: cyl
mpg cyl disp hp drat wt qsec vs am gear carb
1 24.4 4 146.7 62 3.69 3.190 20.00 1 0 4 2
2 26.0 4 120.3 91 4.43 2.140 16.70 0 1 5 2
3 21.0 6 160.0 110 3.90 2.875 17.02 0 1 4 4
4 17.8 6 167.6 123 3.92 3.440 18.90 1 0 4 4
5 14.3 8 360.0 245 3.21 3.570 15.84 0 0 3 4
6 15.0 8 301.0 335 3.54 3.570 14.60 0 1 5 8
更新:
在较新版本的 dplyr 中,sample_n
不再需要 do
函数.当前每组随机抽取两行样本的代码:
The do
function is no longer needed for sample_n
in newer versions of dplyr. Current code for taking a random sample of two rows per group:
mtcars %>%
group_by(cyl) %>%
sample_n(2)
这篇关于使用 dplyr 从数据框中采样子组行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!