mutate_if() with OR conditions dplyr

后端 未结 2 1497
孤街浪徒
孤街浪徒 2021-01-23 16:22

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 a

相关标签:
2条回答
  • 2021-01-23 17:11

    You can use this version of mutate_if

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

    which would convert the double or integer columns to character.

    0 讨论(0)
  • 2021-01-23 17:17

    We can do this with base R

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

    Or using data.table

    library(data.table)
    setDT(storms)[, names(storms) := lapply(.SD, function(x) 
            if(is.numeric(x)) as.character(x) else x)]
    
    0 讨论(0)
提交回复
热议问题