gpt4 book ai didi

使用 dplyr 和 sample_n 根据权重随机抽样

转载 作者:行者123 更新时间:2023-12-02 04:50:06 27 4
gpt4 key购买 nike

我想根据单独数据框中的索引给出的一组权重随机抽样月份,但索引会根据一些分类变量而变化。

下面是一个示例问题:

require(dplyr)
sim.size <- 1000
# Generating the weights for each month, and category combination
class_probs <- data_frame(categoryA=rep(letters[1:3],24)
categoryB=rep(LETTERS[1:2],each=36),
Month=rep(month.name,6),
MonthIndex=runif(72))


# Generating some randomly simulated cateogories
sim.data <- data_frame(categoryA=sample(letters[1:3],size=sim.size,replace=TRUE),
categoryB=sample(LETTERS[1:2],size=sim.size,replace=TRUE))

# This is where i need help
# I would like to add an extra column called Month on the end of sim.data
# That will be sampled using the class_probs data, taking into account the
# Both categoryA and categoryB to generate the weights in MonthIndex
sim.data %>%
group_by(categoryA,categoryB) %>%
do(sample_n(class_probs[class_probs$categoryA==categoryA &
class_probs$categoryB==categoryB, ],
size=nrow(sim.data[sim.data$categoryA==categoryA &
sim.data$categoryB==categoryB]),
replace=TRUE,
weight=MonthIndex)$Month)

因此,对于每个组,我希望能够对 categoryA 和 categoryB 的特定组合的相同次数进行采样,并且对于每次出现的情况,我都希望根据 class_prob 数据子集给出的 MonthIndex 对一个月进行采样。框架...

然后将所选月份绑定(bind)到原始数​​据集 sim.data作为额外的列

希望我的代码已经很接近了...我只需要一些帮助来确定需要更改的内容...

最佳答案

这是一种使用辅助函数进行采样的方法,然后是一个简单的 mutate来电dplyr创建新列。

辅助函数:

sampler <- function(x, y, df) {

tab <- sample_n(df %>% filter(categoryA==x,
categoryB==y),
size=1,
replace=TRUE,
weight=MonthIndex)

return(tab$Month)

}

调用它来创建一个新变量:
sim.data %>%
rowwise() %>%
mutate(month = sampler(categoryA, categoryB, class_probs))

结果:
Source: local data frame [1,000 x 3]
Groups: <by row>

categoryA categoryB month
1 b B February
2 b A February
3 b B May
4 c B December
5 c B June
6 b A August
7 c A March
8 c A September
9 b A August
10 c A December
.. ... ... ...

关于使用 dplyr 和 sample_n 根据权重随机抽样,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29526125/

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