使用apply()通过多个因变量迭代线性回归模型

时间:2019-01-14 13:51:33

标签: r loops dplyr apply

我正在计算模型输出,以对具有45个不同id值的因变量进行线性回归。如何使用整洁的代码(dplyr,apply等)完成此任务?

我有一个数据集,该数据集包含三个变量data = c(iddistanceactPct),使得id == 1:45; -10 <= distance <= 10; 0 <= actsPct <= 1.

我需要对model0n的每个值进行回归id,以使model0n放入新的小标题/ df。我已经完成了一次回归:

model01 <- data %>% 
filter(id == 1) %>%
filter(distance < 1) %>%
filter(distance > -4)
model01 <- lm(data = model01, actPct~distance)

示例数据

set.seed(42)
id <- as.tibble(sample(1:45,100,replace = T))
distance <- as.tibble(sample(-4:4,100,replace = T))
actPct <- as.tibble(runif(100, min=0, max=1))
data01 <- bind_cols(id=id, distance=distance, actPct=actPct)
attr(data01, "col.names") <- c("id", "distance", "actPct")

我希望有一个model01model45的新小标题或数据框,以便将所有回归输出都放在一个表中。

1 个答案:

答案 0 :(得分:2)

您可以将group_by中的nestmutatemaptidyverse结合使用:

data01 %>% 
  group_by(id) %>% 
  nest() %>% 
  mutate(models = map(data, ~ lm(actPct ~ distance, data = .x)))

# A tibble: 41 x 3
#       id data             models  
#    <int> <list>           <list>  
#  1    42 <tibble [3 x 2]> <S3: lm>
#  2    43 <tibble [4 x 2]> <S3: lm>
#  3    13 <tibble [2 x 2]> <S3: lm>
#  4    38 <tibble [4 x 2]> <S3: lm>
#  5    29 <tibble [2 x 2]> <S3: lm>
#  6    24 <tibble [5 x 2]> <S3: lm>
#  7    34 <tibble [5 x 2]> <S3: lm>
#  8     7 <tibble [3 x 2]> <S3: lm>
#  9    30 <tibble [2 x 2]> <S3: lm>
# 10    32 <tibble [2 x 2]> <S3: lm>
# ... with 31 more rows

另请参阅R for R for Data Science中有关许多模型的章节:https://r4ds.had.co.nz/many-models.html

数据

set.seed(42)
id <- sample(1:45, 100, replace = T)
distance <- sample(-4:4, 100, replace = T)
actPct <- runif(100, min = 0, max = 1)
data01 <- tibble(id = id, distance = distance, actPct = actPct)