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

2

1 Answer 1

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", .)))
Sign up to request clarification or add additional context in comments.

1 Comment

@iod To keep the shape (dimensions) of the dataset.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.