Appending a vector using case_when R

Viewed 95

I am trying to add a vector of arguments to a nested dataframe, later to be used as addons to the regression formula I will be running with this data. However, I am not able to.. any thoughts?

library(tidyverse)

flights <- nycflights13::flights
flights<- sample_n(flights, 1000)
nested <- flights %>% group_by(origin, dest) %>% 
  nest() ## groups all the data by the sub series

nested %>% mutate (formula = "airtime ~ distance + carrier")
nested<-nested %>% mutate (add_in = case_when(
  
  origin =="EWR" & dest =="CVG"  ~  list("year", "hour"),
  origin =="EWR" & dest =="LAX"  ~  list("year", "dep_delay")
))

This may have 17-20 different models , with the same basic formula (only addons). is there a cleaner way to do this for 20 models?

1 Answers

We could either have a list

library(dplyr)
nested %>% 
 mutate(add_in =  case_when(
  origin =="EWR" & dest =="CVG"  ~ list(c("sno", "sno2","sno3")),
 origin =="EWR" & dest =="LAX"  ~  list(c("sno", "sno2","sno3"))))

or paste them together (toString -> paste(., collapse=", ")) as a single string

nested %>% 
  mutate(add_in =  case_when(
   origin =="EWR" & dest =="CVG"  ~ toString(c("sno", "sno2","sno3")),
   origin =="EWR" & dest =="LAX"  ~  toString(c("sno", "sno2","sno3"))))

Update

If we need to create a formula object, can do this with paste or reformulate

out <- nested %>%
   mutate(add_in = case_when(
  origin =="EWR" & dest =="CVG"  ~  
     list(reformulate(c("distance", "carrier", "year", "hour"), "airtime")), 
     origin =="EWR" & dest =="LAX" 
     ~ list(reformulate(c("distance", "carrier", "year", 
       "dep_delay"), "airtime")))) 
Related