CGP
CGP

Reputation: 169

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.

Upvotes: 2

Views: 318

Answers (2)

myusername
myusername

Reputation: 31

Here's a method using tidyr 1.3.1:

df1 %>%
    unnest_wider(
        matches("^values2$"),
        names_repair = ~gsub('...', 'values1_', ., fixed = TRUE)
    )

Upvotes: 0

Alexlok
Alexlok

Reputation: 3134

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")

Upvotes: 2

Related Questions