在分组后对变量进行Bootsrap(获取每组的置信区间)

问题描述 投票:0回答:1

我想执行引导函数 boot() 来获取变量 'R_CO_GC' 在按列 'BARRIER_POS' 分组后的置信区间,该列有 3 个值(在过滤器之后)。

首先我定义了我的中值函数来进入启动函数:

mediana_boot <- function(x,i){
  return(median(x[i]))
}

之后,我从“BARRIER_POS”中过滤掉我不感兴趣的值,然后按同一变量对数据框进行分组。后来我使用 mutate 来执行引导程序并计算置信区间。然后我使用汇总来获取中位数,提取下限和上限区间,并将它们与中位数一起保留在数据框中作为最终输出:

lr2_analysis_CO_FIL %>%
  filter(BARRIER_POS != 'no_street') %>%
  group_by(BARRIER_POS) %>% 
  mutate(boot_CO = boot.ci(boot(R_CO_GC, mediana_boot, R = 100), conf = 0.95, type = "bca")) %>% 
  summarise(mediana = median(R_CO_GC),
            CI.L = boot_CO[4],
            CI.U = boot_CO[5]) %>%
  data.frame(mediana, CI.L, CI.U)

但遗憾的是我得到了这个错误:

cnd_bullet_header(action) 中的错误: 承诺已在评估中:递归默认参数引用或早期问题?

我不知道如何解决。有什么想法吗?

我还想添加一列引用 3 个组 (BARRIER_POS),从中我获得了中位数和置信区间。

r boot confidence-interval summarize mutate
1个回答
0
投票

编写一个以小标题形式返回置信区间的函数,并将

summarise
直接应用于它。

library(boot)
library(tidyverse)

mediana_boot <- function(x,i){
  median(x[i])
}
boot_ci_bca <- function(x) {
  b <- boot(x, mediana_boot, R = 1000L)
  ci <- boot.ci(b, conf = 0.95, type = "bca")$bca[4:5]
  names(ci) <- c("lwr", "upr")
  as_tibble(as.list(ci))
}

iris %>%
  group_by(Species) %>%
  summarise(
    mediana = median(Sepal.Length),
    boot_ci_bca(Sepal.Length)
  )
#> Warning: There was 1 warning in `summarise()`.
#> ℹ In argument: `boot_ci_bca(Sepal.Length)`.
#> ℹ In group 1: `Species = setosa`.
#> Caused by warning in `norm.inter()`:
#> ! extreme order statistics used as endpoints
#> # A tibble: 3 × 4
#>   Species    mediana   lwr   upr
#>   <fct>        <dbl> <dbl> <dbl>
#> 1 setosa         5     4.8  5   
#> 2 versicolor     5.9   5.7  6.05
#> 3 virginica      6.5   6.3  6.7

创建于 2024-03-01,使用 reprex v2.0.2

© www.soinside.com 2019 - 2024. All rights reserved.