gpt4 book ai didi

r - dplyr sample_n 按组,每组具有唯一的大小参数

转载 作者:行者123 更新时间:2023-12-02 08:05:58 25 4
gpt4 key购买 nike

我试图从数据集中抽取一个分层样本,其中存在一个变量,表明每组的样本量应该有多大。

library(dplyr)
# example data
df <- data.frame(id = 1:15,
grp = rep(1:3,each = 5),
frq = rep(c(3,2,4), each = 5))

在这个例子中, grp 是指我想要采样的组, frq 是为该组指定的样本大小。

使用 split ,我想出了这个可能的解决方案,它给出了想要的结果,但似乎效率很低:
s <- split(df, df$grp)
lapply(s,function(x) sample_n(x, size = unique(x$frq))) %>%
do.call(what = rbind)

有没有办法只使用 dplyr 的 group_bysample_n 来做到这一点?

我的第一个想法是:
df %>% group_by(grp) %>% sample_n(size = frq)

但这给出了错误:

Error in is_scalar_integerish(size) : object 'frq' not found

最佳答案

library(tidyverse)

# example data
df <- data.frame(id = 1:15,
grp = rep(1:3,each = 5),
frq = rep(c(3,2,4), each = 5))

set.seed(22)

df %>%
group_by(grp) %>% # for each group
nest() %>% # nest data
mutate(v = map(data, ~sample_n(data.frame(id=.$id), unique(.$frq)))) %>% # sample using id values and (unique) frq value
unnest(v) # unnest the sampled values

# # A tibble: 9 x 2
# grp id
# <int> <int>
# 1 1 2
# 2 1 5
# 3 1 3
# 4 2 8
# 5 2 9
# 6 3 14
# 7 3 13
# 8 3 15
# 9 3 11

如果您将 ids(不是 ids 向量)和一个频率值(对于每组)的数据帧作为输入传递,则函数 sample_n 起作用。

使用 map2 并提前为 sample_n 生成输入的替代版本:
df %>%
group_by(grp) %>% # for every group
summarise(d = list(data.frame(id=id)), # create a data frame of ids
frq = unique(frq)) %>% # get the unique frq value
mutate(v = map2(d, frq, ~sample_n(.x, .y))) %>% # sample using data frame of ids and frq value
unnest(v) %>% # unnest sampled values
select(-frq) # remove frq column (if needed)

关于r - dplyr sample_n 按组,每组具有唯一的大小参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51671856/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com