r - 如何展平非原子函数结果,以便可以将其分配为dplyr突变步骤的一部分?

标签 r dplyr tidyverse

在看How to flatten results of function call as part of dplyr::mutate之前,我已经碰到了这个用例。这次有所不同,因为我需要调用的函数不依赖于一组x值。在这里,我正在使用BCa(经偏置校正的加速间隔)来计算自举置信区间,但需要针对每个类阶层对其调用两次,因为需要读取上下限置信区间输出($bca[4]$bca[5])。

if(!require(tidyverse)) install.packages("tidyverse", repos = "http://cran.us.r-project.org")
if(!require(boot)) install.packages("boot", repos = "http://cran.us.r-project.org")
if(!require(purrr)) install.packages("purrr", repos = "http://cran.us.r-project.org")

comp <- data.frame(
  class = sample(c("bronze","silver","gold"),1500,replace=TRUE),
  reputation = rnbinom(1500,mu=100,size=1)+1
)

# function to obtain the mean
bootMean <- function(sample, index) {
  return(mean(sample[index]))
} 

# bootstrapping using 3000 replications
B <- 3000
summaryRep <- comp %>%
  group_by(class) %>%
  summarise(mean=mean(reputation),
            ymin=boot.ci(boot(data=reputation, statistic=bootMean, R=B), type=c("bca"))$bca[4],
            ymax=boot.ci(boot(data=reputation, statistic=bootMean, R=B), type=c("bca"))$bca[5])
summaryRep

我已经尝试了以上文章中提出的解决方案,但它们无法正常工作。首先,因为不可能进行映射,其次,它仍然会提示boot.ci结果的尺寸。

如何避免两次调用boot函数,同时保持dplyr认证的方法,即不采用程序方法?

最佳答案

一种方法是将boot.ci的输出保留在列表中,然后提取相应的值。

library(boot)
library(dplyr)
set.seed(123)

comp %>%
  group_by(class) %>%
 summarise(mean=mean(reputation),
           model = list(boot.ci(boot(data=reputation, statistic=bootMean, R=B), 
                        type=c("bca"))),
           ymin= model[[1]]$bca[4],
           ymax= model[[1]]$bca[5])

# A tibble: 3 x 5
#  class   mean model     ymin  ymax
#  <fct>  <dbl> <list>   <dbl> <dbl>
#1 bronze  103. <bootci>  93.7  112.
#2 gold    102. <bootci>  93.5  111.
#3 silver  100. <bootci>  92.1  109.

关于r - 如何展平非原子函数结果,以便可以将其分配为dplyr突变步骤的一部分?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59478934/

相关文章:

R dplyr : How do I apply a less than/greater than mapping table across a large dataset efficiently?

r - 使用 group_by 时添加整体平均值

r - 将虚拟编码矩阵转换为邻接矩阵

r - 遍历列表时获取列表的元素编号

r - 使用 R 中的 plot() 更改 X 轴上的标签

r - 如何从循环中的列表创建 R 数据框

python - 使用 Python(或 R)提取谷歌学术搜索结果

每个变量的 R 内存使用情况

R:将参数传递给外部()

r - 在 tidyverse 中过滤每组的前 5 个观察值