I have the following setup.
df <- data.frame(aa = rnorm(1000), bb = rnorm(1000))
apply(df, 2, typeof)
# aa bb
#"double" "double"
apply(df, 2, class)
# aa bb
#"numeric" "numeric"
Then I try to convert one of the columns to "factor". But as you can see below, I am not getting any "factor" type or classes. Am I doing anything wrong ?
df[, 1] <- as.factor(df[, 1])
apply(df, 2, typeof)
# aa bb
#"character" "character"
apply(df, 2, class)
# aa bb
#"character" "character"
Sorry I felt my original answer badly written. Why did I put that "matrix of factors" in the very beginning? Here is a better try.
From
?apply
:So a data frame is converted to a matrix by
as.matrix
, beforeFUN
is applied row-wise or column-wise.From
?as.matrix
:I am not a native English speaker and I can't read the following (which looks rather important!). Can someone clarify it?
From
?as.vector
:Simply put, as long as you have a factor column in a data frame,
as.matrix
gives you a character matrix.I believed this
apply
with data frame problem has been raised many times and the above just adds another duplicate answer. Really sorry. I failed to read OP's question carefully. What hit me in the first instance is that R can not build a true matrix of factors.While this is interesting, it should be less-relevant to OP's question.
Sorry again for making a mess here. So bad!!
Use
lapply
actually.sapply
would simplify the result to an array, which is a matrix in 2D case. Here is an example:Regarding
typeof
, factors are actually stored as integers.When you
dput
a factor you can see this. For example:The real values are
1:6
. Character levels are just an attribute.