rdataframedplyrcoalesce

dplyr::coalesce skip non-existent values in R


Is it actually possible to have dplyr::coalesce() skip non-existent values like e.g. colnames in this case? (e.g. col2 doesn't exist in data)

data %>%
  mutate(
    var_1 = coalesce(col1, col2,...,coln),
    var_n = ...)

Thanks


Solution

  • You can store all possible column names into a character vector in advance, then use any_of() to select columns. If some column names do not exist, any_of() will skip them.

    library(dplyr)
    
    vars <- paste0("col", 1:10)
    # [1] "col1"  "col2"  "col3"  "col4"  "col5"  "col6"  "col7"  "col8"  "col9"  "col10"
    
    data %>%
      mutate(
        var_1 = do.call(coalesce, pick(any_of(vars)))
      )
    

    If col1 to coln are in sequence, you can simply use col1:coln to select variables lying between col1 on the left and coln on the right.

    data %>%
      mutate(
        var_1 = do.call(coalesce, pick(col1:col10))
      )