【问题标题】:Use apply() to iterate linear regression models through multiple dependent variables使用 apply() 通过多个因变量迭代线性回归模型
【发布时间】:2019-01-14 13:51:33
【问题描述】:

我正在为具有 45 个不同 id 值的因变量计算线性回归的模型输出。如何使用 tidy(dplyr、apply 等)代码来完成此操作?

我有一个包含三个变量的数据集data = c(iddistanceactPct) 这样id == 1:45; -10 distance actsPct

我需要对id 的每个值运行回归model0n,这样model0n 就会放入一个新的tibble/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")

我希望新的 tibble 或数据框具有 model01:model45,因此我可以将所有回归输出放入一个表中。

【问题讨论】:

  • apply 根据我的经验通常很慢。
  • @NelsonGon,谢谢,我之前没有体验过缓慢的apply 函数。你还有其他喜欢的吗?我读到的所有内容都表明applyfor loop 快,所以我想我会试一试。
  • 你能看看这个问题是否有帮助吗?似乎和你的stackoverflow.com/questions/53968490/… 相似,可能使用apply 家庭的其他成员,但不是apply(个人意见)。

标签: r loops dplyr apply


【解决方案1】:

您可以使用group_bynestmutatemap 中的tidyverse 来完成此操作:

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)

【讨论】:

    猜你喜欢
    • 2019-03-30
    • 1970-01-01
    • 2021-05-13
    • 2020-03-06
    • 1970-01-01
    • 2021-01-15
    • 2023-03-23
    • 2020-05-20
    • 2019-07-17
    相关资源
    最近更新 更多