简体   繁体   中英

Converting to string all values in a data frame in R

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM