- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我想根据单独数据框中的索引给出的一组权重随机抽样月份,但索引会根据一些分类变量而变化。
下面是一个示例问题:
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)
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/
这是来自 R 中 dplyr 的“sample_n”。 https://dplyr.tidyverse.org/reference/sample.html 为了可重复性,我应该放置一个种子,以便其他人
我试图从数据集中抽取一个分层样本,其中存在一个变量,表明每组的样本量应该有多大。 library(dplyr) # example data df % do.call(what = rbi
我想根据单独数据框中的索引给出的一组权重随机抽样月份,但索引会根据一些分类变量而变化。 下面是一个示例问题: require(dplyr) sim.size % group_by(category
我试图以分组的方式将采样函数应用于数据框,如果组大小小于 n,它应该从每个组或所有组成员中采样 n 个样本。 使用dplyr,我第一次尝试 library(dplyr) mtcars %>% grou
根据dplyr帮助文件 sample_n函数对每组采样固定数量。 当我运行以下代码时,我希望每个 tobgp 和 alcgp 组合有两个样本,因此总共有 32 (4*4*2) 行。但是只返回两行。 b
我有以下分组数据框,我想使用函数 dplyr::sample_n从该数据框中为每个组提取行。我想使用分组变量的值NDG在每个组中作为要从每个组中提取的行数。 > dg.tmp dg % d
我是一名优秀的程序员,十分优秀!