简体   繁体   English

dplyr mutate_at 但使用任何而不是全部

[英]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.我想使用mutate_at(col_names,as.numeric)但有时 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 换成不存在的东西,则会出现错误:

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_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). mutate_at已被弃用,现在首选 cross(),它与across() any_of()all_of()辅助函数(以及其他 select 辅助函数)一起使用。

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

See the ?across help page for more options and examples.有关更多选项和示例,请参阅?across帮助页面。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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