我有以下分组数据框,我想使用该功能dplyr::sample_n
从此数据框中为每个组提取行。我想使用分组变量的值NDG
每组中的行数作为从每组中提取的行数。
> dg.tmp <- structure(list(Gene = c("CAMK1", "GHRL", "TIMP4", "CAMK1", "GHRL",
"TIMP4", "ARL8B", "ARPC4", "SEC13", "ARL8B", "ARPC4", "SEC13"
), GLB = c(3, 3, 3, 3, 3, 3, 10, 10, 10, 10, 10, 10), NDG = c(1,
1, 1, 2, 2, 2, 1, 1, 1, 2, 2, 2)), class = c("tbl_df", "tbl",
"data.frame"), row.names = c(NA, -12L), .Names = c("Gene", "GLB",
"NDG"))
> dg <- dg.tmp %>%
dplyr::group_by(GLB,NDG)
> dg
Source: local data frame [12 x 3]
Groups: GLB, NDG
Gene GLB NDG
1 A4GNT 3 1
2 ABTB1 3 1
3 AHSG 3 1
4 A4GNT 3 2
5 ABTB1 3 2
6 AHSG 3 2
7 AADAC 10 1
8 ABHD14B 10 1
9 ACVR2B 10 1
10 AADAC 10 2
11 ABHD14B 10 2
12 ACVR2B 10 2
例如,假设正确的随机选择,我想要代码
> dg %>% dplyr::sample_n(NDG)
输出:
Source: local data frame [6 x 3]
Groups: GLB, NDG
Gene GLB NDG
1 A4GNT 3 1
2 A4GNT 3 2
3 ABTB1 3 2
4 AADAC 10 1
5 AADAC 10 2
6 ABHD14B 10 2
但是,它给出了以下错误:
Error in eval(expr, envir, enclos) : object 'NDG' not found
通过比较,dplyr::slice
当我使用代码时给出正确的输出
> dg %>% dplyr::slice(1:unique(NDG))
It is稍微有点黑客使用unique
然而,在这种情况下,代码
> dg %>% dplyr::slice(1:NDG)
返回以下警告消息
Warning messages:
1: In slice_impl(.data, dots) :
numerical expression has 3 elements: only the first used
2: In slice_impl(.data, dots) :
numerical expression has 3 elements: only the first used
3: In slice_impl(.data, dots) :
numerical expression has 3 elements: only the first used
4: In slice_impl(.data, dots) :
numerical expression has 3 elements: only the first used
显然是因为NDG
正在被评估(在适当的环境中)c(1,1,1)
or c(2,2,2)
, 因此1:NDG
返回上述警告。
关于为什么我收到错误,我知道 Hadley 用于方法sample_n.grouped_df 的代码是
sample_n.grouped_df <- function(tbl, size, replace = FALSE, weight = NULL,
.env = parent.frame()) {
assert_that(is.numeric(size), length(size) == 1, size >= 0)
weight <- substitute(weight)
index <- attr(tbl, "indices")
sampled <- lapply(index, sample_group, frac = FALSE,
tbl = tbl, size = size, replace = replace, weight = weight, .env = .env)
idx <- unlist(sampled) + 1
grouped_df(tbl[idx, , drop = FALSE], vars = groups(tbl))
}
可以在相关的Github页面。因此我得到了错误,因为sample_n.grouped_df
找不到变量NGD
因为它没有在正确的环境中寻找。
因此,有没有一种巧妙的使用方法sample_n
on dg
获得
Source: local data frame [6 x 3]
Groups: GLB, NDG
Gene GLB NDG
1 A4GNT 3 1
2 A4GNT 3 2
3 ABTB1 3 2
4 AADAC 10 1
5 AADAC 10 2
6 ABHD14B 10 2
对每组进行随机抽样?