使用 dplyr 的 sample_n 函数按组采样 [英] Sample by group using the sample_n function of dplyr

查看:19
本文介绍了使用 dplyr 的 sample_n 函数按组采样的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

根据 dplyr 帮助文件,sample_n 函数对每组采样固定数量.

According to the dplyr help file the sample_n function samples a fixed number per group.

当我运行以下代码时,我希望每个 tobgp 和 alcgp 组合有两个样本,因此总共有 32 (4*4*2) 行.但是只返回两行.

When I run the following code I expect two samples per tobgp and alcgp combination, so 32 (4*4*2) lines in total. However only two lines are returned.

by_tobgp_alcgp <- esoph %>% group_by(tobgp,alcgp)

sample_n(by_tobgp_alcgp , 2)


# Source: local data frame [2 x 5]
# Groups: tobgp, alcgp
# 
#    agegp     alcgp tobgp ncases ncontrols
# 10 25-34    80-119 10-19      0         1
# 50 55-64 0-39g/day   30+      4         6

这是正确的吗?有没有其他方法可以使用 dplyr 来实现这一点?

Is this correct? Is there an alternative way to achieve this using dplyr?

推荐答案

issue@Henrik 所描述的已经关闭.

The issue that @Henrik described has been closed.

sample_n 运算符将处理 dplyr 版本 >= 0.3

The sample_n operator will work on grouped data frames for dplyr versions >= 0.3

library(dplyr)
data(esoph)

set.seed(123)

esoph %>%
  group_by(tobgp, alcgp) %>%
  sample_n(2)

#Source: local data frame [32 x 5]
#Groups: tobgp, alcgp [16]
#
#agegp     alcgp    tobgp ncases ncontrols
#(fctr)    (fctr)   (fctr)  (dbl)     (dbl)
#1   65-74 0-39g/day 0-9g/day      5        48
#2   25-34 0-39g/day 0-9g/day      0        40
#3   45-54     40-79 0-9g/day      6        38
#4     75+     40-79 0-9g/day      2         5
#5   55-64    80-119 0-9g/day      9        18
#6   35-44    80-119 0-9g/day      0        11
#7   45-54      120+ 0-9g/day      4         4
#8   65-74      120+ 0-9g/day      3         4
#9   45-54 0-39g/day    10-19      0        18
#10  65-74 0-39g/day    10-19      4        14
#11    75+     40-79    10-19      1         3
#12  55-64     40-79    10-19      6        21
#13  45-54    80-119    10-19      6        14
#14  25-34    80-119    10-19      0         1
#15    75+      120+    10-19      1         1
#16  35-44      120+    10-19      0         3
#17  25-34 0-39g/day    20-29      0         6
#18  55-64 0-39g/day    20-29      3        12
#19  65-74     40-79    20-29      5         9
#20  25-34     40-79    20-29      0         4
#21  55-64    80-119    20-29      3         6
#22  65-74    80-119    20-29      2         3
#23  45-54      120+    20-29      2         3
#24  35-44      120+    20-29      2         4
#25  55-64 0-39g/day      30+      4         6
#26  35-44 0-39g/day      30+      0         8
#27  35-44     40-79      30+      0         8
#28  25-34     40-79      30+      0         7
#29  35-44    80-119      30+      0         1
#30  55-64    80-119      30+      4         4
#31  25-34      120+      30+      0         2
#32  65-74      120+      30+      1         1

这篇关于使用 dplyr 的 sample_n 函数按组采样的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆