Mayou
Mayou

Reputation: 8818

Odd behavior when converting columns of dataframe to factors

I am trying to convert all the columns of a dataframe to factors. However, the conversion to factors make all my entries become string instead of numeric. See example:

df <- data.frame(a = c(1,2,3), b = c(4,5,6))
df_factor <- apply(df, 2, factor)

This is what I get:

 #> df_factor
 #     a   b  
 #[1,] "1" "4"
 #[2,] "2" "5"
 #[3,] "3" "6"

Would you have an idea as to where the problem is coming from?

Thanks,

Upvotes: 1

Views: 91

Answers (2)

Henrik
Henrik

Reputation: 67778

A plyr alternative:

library(plyr)
df2 <- colwise(factor)(df)

Upvotes: 0

Ferdinand.kraft
Ferdinand.kraft

Reputation: 12819

apply(df, 2, factor) changes your dataframe to a matrix. Use this instead:

df_factor <- as.data.frame(lapply(df, factor))

Upvotes: 1

Related Questions