0

How can I make sure each single value contained in a dataframe is a string?

Moreover, is there a way I can add a prefix to each value contained in a dataframe? (for example, turning a 0.02 to "X0.02")

Robb1
  • 4,587
  • 6
  • 31
  • 60
  • Possible duplicate of [Convert type of multiple columns of a dataframe at once](https://stackoverflow.com/questions/7680959/convert-type-of-multiple-columns-of-a-dataframe-at-once) – NelsonGon Jun 07 '19 at 16:04
  • Perhaps there's a better duplicate. The above is a bit too complex. – NelsonGon Jun 07 '19 at 16:06

1 Answers1

3

We can loop through the columns of the data.frame with lapply, convert to character and assign the output back to the dataset. The [] is used to preserve the attributes of the original data and not output as a list element

dat[] <- lapply(dat, as.character)

Or if there is at least one character element, conversion to matrix and then back to data.frame will also make sure the elements are character

as.data.frame(as.matrix(dat), stringsAsFactors = FALSE)

For the second case

dat[] <- lapply(dat,function(x) paste0("X", x))

Or in tidyverse

library(dplyr)
library(stringr)
dat %>%
   mutate_all(list(~ str_c("X", .)))
akrun
  • 874,273
  • 37
  • 540
  • 662