我的数据是这样的:特定值的一个数据帧的总和高效采样
df <- data.frame(
x = c("dog", "dog", "dog", "cat", "cat", "fish", "fish", "fish", "squid", "squid", "squid"),
y = c(10, 11, 6, 3, 4, 5, 5, 9, 14, 33, 16)
)
我想通过数据进行迭代,并在某些“列入/过滤器”列表抓住每个动物的一个值,然后将它们相加。
例如,也许我只关心狗,猫和鱼。
animals <- c("dog", "cat", "fish")
在再取样1,我能得到10,图4,图9(总和= 23),并在再取样2我能得到6,3,5(总和= 14)。
我刚刚刮起了真正janky重复/为上dplyr
倾斜功能,但它似乎超级低效:
ani_samp <- function(animals){
total <- 0
for (i in animals) {
v <- df %>%
filter(x == i) %>%
sample_n(1) %>%
select(y) %>%
as.numeric()
total <- total + v
}
return(total)
}
replicate(1000,ani_samp(animals))
我会如何改善这种采样/伪引导代码?