简体   繁体   English

带有OR条件dplyr的mutate_if()

[英]mutate_if() with OR conditions dplyr

If I want to convert an integer or double variables to character variables, how can I accomplish the task, I tried the below code, but I am certain this is an incorrect way. 如果要将integerdouble变量转换为character变量,如何完成任务,请尝试以下代码,但是我确定这是错误的方法。

storms %>% mutate_if(c(is.integer | is.double),
                     .funs = as.character)

You can use this version of mutate_if 您可以使用此版本的mutate_if

library(dplyr)
storms %>% mutate_if(~ is.double(.) | is.integer(.), as.character)

which would convert the double or integer columns to character. 它将双精度或整数列转换为字符。

We can do this with base R 我们可以使用base R

storms[] <- lapply(storms, function(x) if(is.numeric(x)) as.character(x) else x)

Or using data.table 或使用data.table

library(data.table)
setDT(storms)[, names(storms) := lapply(.SD, function(x) 
        if(is.numeric(x)) as.character(x) else x)]

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

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