梳理tidyverse+调查[R]:如何在Nest-Map-Unnest-Chain中使用svyglm?

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

我目前正在努力在R中对多个变量运行加权回归模型。

当使用(非加权)glm时,我通过运行以下内容获得成功。

mtcars_1 <- mtcars %>%
  nest(-gear)%>%
  mutate(model_0      = map(data, ~ glm(vs ~ drat, family = "binomial", data = .)))%>%
  mutate(model_0_tidy = map(model_0, tidy))%>%
  select(gear, model_0_tidy)%>%
  ungroup()%>%
  unnest(model_0_tidy)

也就是我得到了以下结果

# A tibble: 6 x 6
   gear term        estimate std.error statistic p.value
  <dbl> <chr>          <dbl>     <dbl>     <dbl>   <dbl>
1     4 (Intercept)  -15.3       22.6     -0.677   0.499
2     4 drat           4.26       5.76     0.740   0.459
3     3 (Intercept)   -3.91       7.39    -0.529   0.597
4     3 drat           0.801      2.32     0.345   0.730
5     5 (Intercept)    5.20      14.4      0.362   0.718
6     5 drat          -1.71       3.77    -0.453   0.651

然而,当我想对我的观测值进行加权,从而使用... ... svyglm 的调查包,嵌套是行不通的。

这是我的方法。

design_0 <- svydesign(ids=~0, data = mtcars, weights = mtaars$wt)

mtcars_2 <- mtcars%>%
  nest(-gear)%>%
  mutate(model_1 = map(data, ~ svyglm(vs ~ drat, family = quasibinomial(logit), design = design_0, data = .)))%>%
  mutate(model_1_tidy = map(model_1, tidy))%>%
  select(gear, model_1_tidy)%>%
  ungroup()%>%
  unnest(model_1_tidy)

# If suggested that wt serves as frequency weight

# Outcome

   gear term        estimate std.error statistic p.value
  <dbl> <chr>          <dbl>     <dbl>     <dbl>   <dbl>
1     4 (Intercept)    -8.12      3.88     -2.09  0.0451
2     4 drat            2.12      1.07      1.99  0.0554
3     3 (Intercept)    -8.12      3.88     -2.09  0.0451
4     3 drat            2.12      1.07      1.99  0.0554
5     5 (Intercept)    -8.12      3.88     -2.09  0.0451
6     5 drat            2.12      1.07      1.99  0.0554

每种装备(即3、4、5)的估计结果都是一样的。

看来这里基本上忽略了嵌套的问题。

有什么办法可以把svyglm和nest-map-unnest结合起来吗?还是我必须寻找其他不那么舒服的方法?

谢谢您

r tidyverse nested-loops glm
1个回答
0
投票

试着这样做

  mtcars%>%
  nest(-gear) %>% 
  mutate(design = map(data, ~ svydesign(ids=~0, data = .x, weights = ~ wt)),
         model = map(.x = design,
                     .f = ~ svyglm(vs ~ drat,
                                   family = quasibinomial(logit),
                                   design = .x))) %>% 
  mutate(model_tidy = map(model, tidy)) %>% 
  select(gear, model_tidy)%>%
  ungroup()%>%
  unnest(model_tidy)
© www.soinside.com 2019 - 2024. All rights reserved.