Search code examples
rtidyrunnest

unnest_wider only if columns exists in R


I would like to unnest_wider conditionally depending on whether a column exists in the data. If the column exists, then it should unnest_wider, but if not, then it shouldn't do anything. I'd hoped that I could do something like:

df1 <- tibble(letters = c('a', 'b', 'c'), values1 = list(1:2, 3:4, 5:6))  

# works
df1 %>% unnest_wider(values1, names_repair = ~gsub('...', 'values1_', ., fixed = TRUE)) 

# doesn't work
df1 %>% unnest_wider(across(any_of("values2")), names_repair = ~gsub('...', 'values1_', ., fixed = TRUE)) 

I know why the last code line doesn't work, but I'd like to accomplish something similar. Thanks.


Solution

  • Would something like that work:

    conditional_unnest <- function(df, var){
      if(var %in% names(df)){
        return(unnest_wider(df, var, names_repair = ~gsub('...', 'values1_', ., fixed = TRUE)))
      } else{
        return(df)
      }
    }
    
    df1 %>%
      conditional_unnest("values1")