遍历调查中的变量组 - R

Iterate through groups of variables in a survey - R

here 所示,如果你想计算惊人的 srvyr 包 中分类变量的比例,你首先必须 group 将变量作为因子,然后使用空的 srvyr::survey_mean,如本例所示。

我的目标是迭代第二个变量 cnamesch.wide 同时保持第一个分组变量 stype 以避免重复代码。

library(survey)
library(srvyr)

data(api)

df <- apiclus1 %>% 
  mutate(cname=as.factor(cname)) %>% 
  select(pw,stype, cname,sch.wide) %>% 
  as_survey_design(weights=pw) 

# proportions of sch.wide
df %>% 
  group_by(stype,sch.wide) %>% 
  summarise(prop=srvyr::survey_mean())
#> # A tibble: 6 x 4
#>   stype sch.wide   prop prop_se
#>   <fct> <fct>     <dbl>   <dbl>
#> 1 E     No       0.0833  0.0231
#> 2 E     Yes      0.917   0.0231
#> 3 H     No       0.214   0.110 
#> 4 H     Yes      0.786   0.110 
#> 5 M     No       0.32    0.0936
#> 6 M     Yes      0.68    0.0936

# proportions of cname
df %>% 
  group_by(stype,cname) %>% 
  summarise(prop=srvyr::survey_mean())
#> # A tibble: 33 x 4
#>    stype cname          prop prop_se
#>    <fct> <fct>         <dbl>   <dbl>
#>  1 E     Alameda     0.0556  0.0191 
#>  2 E     Fresno      0.0139  0.00978
#>  3 E     Kern        0.00694 0.00694
#>  4 E     Los Angeles 0.0833  0.0231 
#>  5 E     Mendocino   0.0139  0.00978
#>  6 E     Merced      0.0139  0.00978
#>  7 E     Orange      0.0903  0.0239 
#>  8 E     Plumas      0.0278  0.0137 
#>  9 E     San Diego   0.347   0.0398 
#> 10 E     San Joaquin 0.208   0.0339 
#> # ... with 23 more rows
Created on 2019-11-28 by the reprex package (v0.3.0)

也许这里的方法是创建列表,保留第一个分组变量并将数据除以另一组变量,然后计算比例。

我想找到涉及 purrr:maptidyverse 的解决方案。

在此先感谢您的帮助,或指出答案!

有多种方法。如果我们作为字符串传递,一种选择是使用 group_by_at 将字符串作为参数

library(purrr)
library(dplyr)
library(survey)
library(srvyr)
map(c('sch.wide', 'cname'), ~
        df %>%
           group_by_at(vars("stype", .x)) %>%
           summarise(prop = srvyr::survey_mean()))
#[[1]]
# A tibble: 6 x 4
#  stype sch.wide   prop prop_se
#  <fct> <fct>     <dbl>   <dbl>
#1 E     No       0.0833  0.0231
#2 E     Yes      0.917   0.0231
#3 H     No       0.214   0.110 
#4 H     Yes      0.786   0.110 
#5 M     No       0.32    0.0936
#6 M     Yes      0.68    0.0936

#[[2]]
# A tibble: 30 x 4
#   stype cname          prop prop_se
#   <fct> <fct>         <dbl>   <dbl>
# 1 E     Alameda     0.0556  0.0191 
# 2 E     Fresno      0.0139  0.00978
# 3 E     Kern        0.00694 0.00694
# 4 E     Los Angeles 0.0833  0.0231 
# 5 E     Mendocino   0.0139  0.00978
# 6 E     Merced      0.0139  0.00978
# 7 E     Orange      0.0903  0.0239 
# 8 E     Plumas      0.0278  0.0137 
# 9 E     San Diego   0.347   0.0398 
#10 E     San Joaquin 0.208   0.0339 
# … with 20 more rows

或者另一种选择是用 quos 包装以创建一个 quosure 列表并在 group_by

中对其进行评估 (!!)
map(quos(sch.wide, cname), ~  
        df %>%
          group_by(stype, !!.x) %>% 
          summarise(prop = srvyr::survey_mean()))