rfor-loopdplyrworkflowrecipe

How to rewrite a mutate + case_when statement with a for loop (R)


I am working on a project that assigns multiple ARIMA models to my data segmented by a grouping variable. Here is a reproducible example which runs as expected:

#Load libraries
library(dplyr)
library(workflows)
library(tidyr)
library(recipes)
library(parsnip)
library(tidymodels)
library(modeltime)
library(purrr)

#Set up data
df <- m750 %>%
  mutate(year = lubridate::year(date)) %>%
  filter(year>=2007 & year <=2009) %>%
  select(c(-id))


#Nest data by year
df_nest <- df %>%
  drop_na() %>%
  nest(data_full = c(-year))


#Create recipes
rec_year_list <- list()
num_years <- length(unique(df$year))

for (i in 1:num_years){
  rec_year_list[[i]] <- recipe(value ~ date, data = df_nest$data_full[[i]])
}

#Assign recipes to workflows
wfl_list <- workflow()

for (i in 1:num_years){
  
  wfl_list[[i]] <- wfl_list %>%
    add_recipe(rec_year_list[[i]]) %>%
    add_model(
      arima_reg() %>%
        set_engine(engine='auto_arima')
    )
}

#Assign workflows to data
df_nest <- df_nest %>%
  mutate(workflow = case_when(year==2007 ~ list(wfl_list[[1]]),
                              year==2008 ~ list(wfl_list[[2]]),
                              year==2009 ~ list(wfl_list[[3]])
                              )
         )

In this example, it's not a big deal to use the mutate and case_when functions since I only have 3 values of my grouping variable. However, in my actual data, I have many values for the grouping variable (ie: >3000). How could I rewrite this last chunk of code as a for loop to properly assign an element of wfl_list to the proper grouping variable as a value in a new column in df_nest.


Solution

  • Try

    df_nest$workflow <- vector('list', nrow(df_nest))
    for(i in seq_len(nrow(df_nest))) 
        df_nest$workflow[i] <- list(wfl_list[[i]])
    

    -output

    > df_nest
    # A tibble: 3 × 3
       year data_full         workflow  
      <dbl> <list>            <list>    
    1  2007 <tibble [12 × 2]> <workflow>
    2  2008 <tibble [12 × 2]> <workflow>
    3  2009 <tibble [12 × 2]> <workflow>