Skip to content
Prev 348613 / 398500 Next

format selected columns in dataframe as character

Of course you could have created them as character vectors in the first
place:

dfx <- data.frame(
  group = c(rep('A', 8), rep('B', 15), rep('C', 6)),
  sex = sample(c("M", "F"), size = 29, replace = TRUE),
  age = runif(n = 29, min = 18, max = 54),
  stringsAsFactors=FALSE
  )


But if that is not possible in your context, then I would suggest this:

for (nm in names(dfx))
   if (is.factor(dfx[[nm]])) dfx[[nm]] <- as.character(dfx[[nm]])

It's clear and simple.