Convert all columns to characters in a data.frame

userJT picture userJT · May 4, 2017 · Viewed 37.1k times · Source

Consider a data.frame with a mix of data types.

For a weird purpose, a user needs to convert all columns to characters. How is it best done? A tidyverse attempt at solution is this:

map(mtcars,as.character) %>% map_df(as.list) %>% View()
c2<-map(mtcars,as.character) %>% map_df(as.list)

when I call str(c2) it should say a tibble or data.frame with all characters.

The other option would be some parameter settings for write.csv() or in write_csv() to achieve the same thing in the resulting file output.

Answer

Jake Thompson picture Jake Thompson · May 5, 2017

You can also use dplyr::mutate_all.

library(dplyr)
mtcars %>%
  mutate_all(as.character)