我想为许多组估计许多线性回归。我使用tidyverse,所以尝试了purrr
的map
和broom
的tidy
。
但是,并非所有小组都对所有模型中的所有变量都具有观察结果。在下面的示例中,当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创建
在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)