Data.frame converted to characters when making it into a matrix. Why?

When I convert my data.frame into a matrix, everything is changed into characters. Why? And how do I stop that from happening?

My data:

value = c(2L,3L,2L,4L,2L,1L,3L,2L,1L,2L,4L,
time = as.factor(c("before","before",
student = as.factor(c("A","B","C","D","E",


by definition a matrix has to be all in one consistent type. so a mix of numeric and character data will become character.


As Nirgrahamuk explains

Seems like as.matrix coerces factors to character, leading to the entire matrix becoming a character matrix. The safest way to avoid this is to either recode the two factor variables to numeric or integer (I believe as.numeric() will work) or to use dummy encoding (p-1 columns where in each row, exactly one entry is set to 1 in the column corresponding to the factor level).

Also, is there a particular reason why you need to convert the data.frame() to a matrix?

Thank you for the replies.

Yes, there are statistical tests that require the data to be in a matrix format.

This topic was automatically closed 21 days after the last reply. New replies are no longer allowed.

If you have a query related to it or one of the replies, start a new topic and refer back with a link.