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")
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")
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", .)))