1

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.

storms %>% mutate_if(c(is.integer | is.double),
                     .funs = as.character)
Shoaibkhanz
  • 1,942
  • 3
  • 24
  • 41
  • You can use a custom function as the predicate, such as one that returns true for either of those conditions. Beyond that, you probably want a [reproducible example](https://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example) – camille Dec 28 '18 at 17:02

2 Answers2

8

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.

Ronak Shah
  • 377,200
  • 20
  • 156
  • 213
2

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)]
akrun
  • 874,273
  • 37
  • 540
  • 662