[当某些模型的某些组为空时,使用purrr映射按组估计线性回归

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

我想为许多组估计许多线性回归。我使用tidyverse,所以尝试了purrrmapbroomtidy

但是,并非所有小组都对所有模型中的所有变量都具有观察结果。在下面的示例中,当z为2时缺少t,因此当lm为2时y ~ x + z无法估计t。我认为每个filter中的lm语句都可以解决问题。但是,有时filter提供了一个空数据集,并且lm引发了错误。

我以为map可以处理这些情况,但我在帮助文件中看不到。

这里有最佳实践吗? FWIW,我只想要系数估计。如果交换注释的mutate,则代码将按预期工作。

library(tidyverse)


df <- tibble(t = rep(1:2, each = 10),
             y = runif(20),
             x = runif(20)) %>%
    mutate(z = ifelse(t == 1, NA, runif(20)))
    # mutate(z = runif(20))


results <- df %>%
    nest(dat = -t) %>%
    mutate(
        model_1 = map(dat, ~ lm(y ~ x, data = .x %>% drop_na(y, x))),
        model_2 = map(dat, ~ lm(y ~ x + z, data = .x %>% drop_na(x, z))),
        coef_1 = map(model_1, tidy),
        coef_2 = map(model_2, tidy)
    ) %>%
    select(t, starts_with('coef')) %>% 
    pivot_longer(
        cols = starts_with('coef')
    ) %>% 
    unnest(value)
#> Error in lm.fit(x, y, offset = offset, singular.ok = singular.ok, ...): 0 (non-NA) cases

reprex package(v0.3.0)在2020-05-15创建

r purrr
1个回答
0
投票

unnest中,默认值为keep_empty = FALSE

library(dplyr)
library(purrr)
library(tidyr)
df %>%
  nest(dat = -t) %>%
  mutate(
    model_1 = map(dat, ~ lm(y ~ x, data = .x %>% drop_na(y, x))),
    model_2 = map(dat, ~ lm(y ~ x + z, data = .x %>% drop_na(x, z))),
    coef_1 = map(model_1, tidy),
    coef_2 = map(model_2, tidy)
    ) %>%
  select(t, starts_with('coef')) %>% 
  pivot_longer(
       cols = starts_with('coef')
     ) %>% 
  unnest(value, keep_empty = TRUE)
© www.soinside.com 2019 - 2024. All rights reserved.