简体   繁体   中英

dplyr mutate_at but using any instead of all

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().

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM