1

How can I convert only the character variables in a R data.frame to factor, without using the dplyr function mutate_if? I tried the following but it doesn't work:

df <- data.frame(w=c(1, 2, 3), x=c(4, 5, 6), y=c('7', '8', '9'), z=c('10', '11', '12'), stringsAsFactors = F)
str(df)
'data.frame':   3 obs. of  4 variables:
 $ w: num  1 2 3
 $ x: num  4 5 6
 $ y: chr  "7" "8" "9"
 $ z: chr  "10" "11" "12"

df[sapply(df, is.character)] <- sapply(df[sapply(df, is.character)], as.factor)
str(df)
'data.frame':   3 obs. of  4 variables:
 $ w: num  1 2 3
 $ x: num  4 5 6
 $ y: chr  "7" "8" "9"
 $ z: chr  "10" "11" "12"
Gaurav Bansal
  • 5,221
  • 14
  • 45
  • 91

1 Answers1

0

it is easier with mutate_if

df %>%
   mutate_if(is.character, factor)

In the OP's code, they used sapply, which converts to matrix and matrix can hold only a single class. it is better to use lapply

i1 <- sapply(df, is.character)
df[i1] <- lapply(df[i1], factor)
akrun
  • 874,273
  • 37
  • 540
  • 662