使用Purrr对同一模型规格进行多次筛选和估算

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

我有一个数据集,我想用它来估计一些线性模型。可以使用下面的代码复制数据。

set.seed(123)
df <- tibble(
  location= c(rep("A",5),rep("B",5), rep("C",5), 
              rep("D",5), rep("E",5), rep("F",5),
              rep("G",5), rep("H",5), rep("I",5),
              rep("J",5)),
  year = rep(c(2017,2018,2019,2020,2021),10),
  w = rnorm(50),  
  x = rnorm(50),
  y = rnorm(50),
  z = rnorm(50)
)

它将具有以下外观

地点 w x y z
A 2017 -0.560 0.253 -0.710 0.788
A 2018 -0.230 -0.0285 0.257 0.769
A 2019 1.56 -0.0429 -0.247 0.332
A 2020 -0.230 -0.0285 0.257 0.769
A 2021 -0.230 -0.0285 0.257 0.769
B 2017 -0.560 0.253 -0.710 0.788
B 2018 -0.230 -0.0285 0.257 0.769
B 2019 1.56 -0.0429 -0.247 0.332
B 2020 -0.230 -0.0285 0.257 0.769
B 2021 -0.230 -0.0285 0.257 0.769

我想分别使用 yz 作为所有年份的解释变量来运行具有两个因变量(wx)的模型,并获得参数估计值的分布。基本上,最后我希望有一个数据框来对每个因变量进行多年来的估计。

我最初考虑的方法包括单独运行模型,为每个模型重复相同的步骤,然后组合来自这些单独数据帧的行。然而,我想利用 purrr 的功能来编写高效的代码。

这是我迄今为止编写的代码。

library(tidyverse)
library(tidymodels)

dependent_vars<- c("w","x")
model_1 <- reformulate(termlabels = c("y","z"), response = dependent_vars[1] )

lm_mod <- linear_reg()

lm_fit_2017_w <- 
  lm_mod %>% 
  fit(model_1, data = df %>% filter (year==2017)) %>%
  tidy() %>% 
  mutate(year=2017, response= dependent_vars[1])

# Repeat this for the rest of the years as well as for x and finally bind the rows

我遇到过一些处理相同类型问题但仅具有不同因变量或预测器的资源stackoverlow问题博客

提前感谢您的帮助。

r purrr tidymodels
1个回答
0
投票

我首先生成一个包含年份和因变量的所有可能组合的 data.frame,然后将其与

pmap
一起使用,它可以同时采用两个或多个输入变量。

我附上了一个未经测试的解决方案,带有

tidymodels
(目前无法安装),而没有测试过的解决方案:

set.seed(123)
df <- tibble(
  location= c(rep("A",5),rep("B",5), rep("C",5), 
              rep("D",5), rep("E",5), rep("F",5),
              rep("G",5), rep("H",5), rep("I",5),
              rep("J",5)),
  year = rep(c(2017,2018,2019,2020,2021),10),
  w = rnorm(50),  
  x = rnorm(50),
  y = rnorm(50),
  z = rnorm(50)
)

dependent_vars<- c("w","x")
years <- unique(df$year)

library(purrr)
library(dplyr)

possible_combinations <- expand.grid(year = years, dependent_var = dependent_vars,
                                     stringsAsFactors = FALSE)

possible_combinations %>% 
  pmap(function(year, dependent_var) {
    data_model <- df %>% 
      filter(year == year)
    model_formula <- as.formula(paste0(dependent_var, " ~ y + z"))
    res <- lm(model_formula, data = data_model)
    tibble(res = list(res), year = year, dependent_var = dependent_var)
  }) %>% 
  bind_rows()

library(tidymodels)

lm_mod <- linear_reg()

possible_combinations %>% 
  pmap(function(year, dependent_var) {
    data_model <- df %>% 
      filter(year == year)
    model_formula <- as.formula(paste0(dependent_var, " ~ y + z"))
    lm_mod %>% 
      fit(model_formula, data = data_model) %>% 
      tidy() %>% 
      mutate(year = year, dependent_var = dependent_var)
  }) %>% 
  bind_rows()
© www.soinside.com 2019 - 2024. All rights reserved.