在 r 调查包中使用 svyby 时在 svymean 中设置自定义置信度

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

我正在运行代码来按组查找加权平均值,并为数据集中的多个变量设置置信区间。我的代码如下所示,使用 mtcars 包进行演示:

library(survey)
library(tidyverse)
var_list = c("wt","qsec")
  
svy_design <- svydesign(
  ids = ~1, 
  data = mtcars |> 
    dplyr::select(cyl,all_of(var_list),mpg) |> 
    na.omit(),
  weights =  mtcars |> 
    dplyr::select(cyl,all_of(var_list),mpg) |> 
    na.omit() |> select(mpg)
)

lapply(var_list, function( x ) svyby(as.formula( paste0( "~" , x ) ) ,
                     by = ~cyl, 
                     design = svy_design, 
                     FUN = svymean,
                     keep.names = FALSE, vartype = "ci")) %>% 
  bind_rows() |> relocate(wt, .after = last_col()) %>%  pivot_longer(!c(cyl,ci_l,ci_u),names_to = "var",values_to = "mean",values_drop_na = TRUE)


这工作得很好,并为每个变量生成所需的置信区间结果。但是,当我尝试将置信区间从默认值 0.95 切换时,我收到错误:

library(survey)
library(tidyverse)
var_list = c("wt","qsec")
  
svy_design <- svydesign(
  ids = ~1, 
  data = mtcars |> 
    dplyr::select(cyl,all_of(var_list),mpg) |> 
    na.omit(),
  weights =  mtcars |> 
    dplyr::select(cyl,all_of(var_list),mpg) |> 
    na.omit() |> select(mpg)
)

lapply(var_list, function( x ) svyby(as.formula( paste0( "~" , x ) ) ,
                     by = ~cyl, 
                     design = svy_design, 
                     FUN = svymean(level = 0.99),
                     keep.names = FALSE, vartype = "ci")) %>% 
  bind_rows() |> relocate(wt, .after = last_col()) %>%  pivot_longer(!c(cyl,ci_l,ci_u),names_to = "var",values_to = "mean",values_drop_na = TRUE)

Error in svymean(level = 0.99) : 
  argument "design" is missing, with no default

如何在

svymean
内使用
svyby
并设置自定义置信区间水平?

r function survey confidence-interval
1个回答
0
投票

第一个问题是

FUN
必须是一个以公式和设计作为前两个参数的函数,因此您应该只向
FUN = svymean
内的
FUN
提供
...
和任何其他参数。

然而,置信区间实际上是通过在

vartype = "ci"
中设置
svyby
来计算的,它在内部调用
survey:::confint.svyby
,并且不会暴露对置信水平的任何控制。

您可以通过单独计算 CI 来解决这个问题:

step1 <- lapply(var_list, \(x) {
  ## Just a standard error - do NOT change vartype=... here!
  d1 <- svyby(as.formula(paste0("~", x)) ,
              by = ~cyl, 
              design = svy_design, 
              FUN = svymean,
              keep.names = FALSE)
  ## NOW calculate the CI with the desired level
  d2 <- confint(d1, level = .99)
  ## Combine results
  d1[,c("ci_l", "ci_u")] <- d2
  dplyr::select(d1, -"se")
})

管道的其余部分保持不变:

bind_rows(step1) %>%
  relocate(wt, .after = last_col()) %>%
  pivot_longer(!c(cyl, ci_l, ci_u),
               names_to = "var",
               values_to = "mean",
               values_drop_na = TRUE)

#> A tibble: 6 × 5
#>     cyl  ci_l  ci_u var    mean
#>   <dbl> <dbl> <dbl> <chr> <dbl>
#> 1     4  1.80  2.64 wt     2.22
#> 2     6  2.78  3.43 wt     3.10
#> 3     8  3.48  4.36 wt     3.92
#> ...
© www.soinside.com 2019 - 2024. All rights reserved.