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"