Home > Back-end >  dplyr mutate_at but using any instead of all
dplyr mutate_at but using any instead of all

Time:09-13

I want to use mutate_at(col_names,as.numeric) but sometimes a column isn't included in the dataframe. For example the following works fine:

df <- data.frame('a'=c('1','2','3'),
           'b'=c('1','2','3'),
           'c'=c(1,2,3),
           'd'=c('1','2','3'))

col_names=c('a','b','d')

df |> mutate_at(col_names,as.numeric)

But if instead I swap out one of the col_names for something that isn't there, I get an error:

col_names=c('a','b','frog')

df |> mutate_at(col_names,as.numeric)

Error: Can't subset columns that don't exist.
x Column `frog` doesn't exist.

Ultimately I think what I'm looking for is something like mutate_any().

CodePudding user response:

mutate_at has been deprecated, across() is now preferred which works with the any_of() and all_of() helper functions (and other select helpers).

df |> mutate(across(any_of(col_names), as.numeric))

See the ?across help page for more options and examples.

  • Related