0

I have a data frame with 8 columns and 40 rows. All columns have numeric values. I need to change column 1 to 5 to character. I tried dplyr::mutate_at() but I cannot get it to work. I don't want to create new columns, but change the class of the existing ones. I keep getting the error Column col1 must be length 40 (the number of rows) or one, not 0

What is the right way to do this with dplyr? I guess I could just do

df$col1 <- as.character(df$col1)

for each of the columns, but I would like to learn the power of dplyr.

Any help is always appreciated. Thanks!!

user10577351
  • 67
  • 1
  • 5
  • "I tried `dplyr::mutate_at()` but I cannot get it to work". Can you post the code you tried that didn't work? Also, please provide the dataframe by copy and pasting the output of `dput(mydata)` into your question. – acylam Nov 02 '18 at 18:24
  • Try `df[1:5] <- lapply(df[1:5], as.character)` – Ronak Shah Nov 02 '18 at 18:25

1 Answers1

4

Try doing it the way below:

df <- data.frame(a = c(0, 0, 0), b = c(1, 1, 1), c = c(0, 0, 1), d = c(1, 1, 1), e = c(0, 0, 0))

df_updated <- df %>% mutate_at(vars(1:5), as.character)
arg0naut91
  • 14,574
  • 2
  • 17
  • 38