Fixing List Objects in R with tidymodels: A Simple yet Crucial Improvement

The problem arises because you used c() to create a list of objects, whereas list() should be used instead.

In R, when creating a new object, it is generally recommended to use list(), especially when working with lists or data frames. This is because list() allows you to specify each element of the list individually and check for their existence within the list, whereas c() combines elements into an existing vector (in this case, the result of fit(lm_spec)).

Therefore, replace:

set.seed(123)

library(olsrr)
library(tidymodels)

y1 <- rnorm(100) + runif(100)
y2 <- rnorm(100) + runif(100)
y3 <- rnorm(100) + runif(100)
x <- rnorm(100)
df1 <- data.frame(y1, y2, y3, x)

lm_spec <- linear_reg()
lm_fit1 <- fit(lm_spec, y1 ~ x, data = df1)
lm_fit2 <- fit(lm_spec, y2 ~ x, data = df1)
lm_fit3 <- fit(lm_spec, y3 ~ x, data = df1)

list_tidymodels <- list(lm_fit1, lm_fit2, lm_fit3) # this line used `c(lm_fit1, ...)`.

get_lm_coefs <- function(x) {
  x %>% 
    # get the lm model object
    extract_fit_engine() %>% 
    # transform its format
    tidy()
}

map(list_tidymodels, get_lm_coefs)

with:

set.seed(123)

library(olsrr)
library(tidymodels)

y1 <- rnorm(100) + runif(100)
y2 <- rnorm(100) + runif(100)
y3 <- rnorm(100) + runif(100)
x <- rnorm(100)
df1 <- data.frame(y1, y2, y3, x)

lm_spec <- linear_reg()
lm_fit1 <- fit(lm_spec, y1 ~ x, data = df1)
lm_fit2 <- fit(lm_spec, y2 ~ x, data = df1)
lm_fit3 <- fit(lm_spec, y3 ~ x, data = df1)

list_tidymodels <- list(lm_fit1, lm_fit2, lm_fit3) # this line used `list()` instead of `c()`

get_lm_coefs <- function(x) {
  x %>% 
    # get the lm model object
    extract_fit_engine() %>% 
    # transform its format
    tidy()
}

map(list_tidymodels, get_lm_coefs)

By replacing c() with list(), you can avoid errors and create a new list of objects correctly.


Last modified on 2024-11-02