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

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

My data:

data.frame(
value = c(2L,3L,2L,4L,2L,1L,3L,2L,1L,2L,4L,
5L,3L,4L,4L,4L,3L,3L,3L,3L,3L,3L,4L,4L,3L,3L,4L,
3L,4L,3L,3L,2L,3L,4L,2L,2L,2L,1L,2L,2L),
time = as.factor(c("before","before",
"before","before","before","before","before",
"before","before","before","1dayafter","1dayafter",
"1dayafter","1dayafter","1dayafter","1dayafter",
"1dayafter","1dayafter","1dayafter","1dayafter",
"1weekafter","1weekafter","1weekafter","1weekafter",
"1weekafter","1weekafter","1weekafter","1weekafter",
"1weekafter","1weekafter","1monthafter",
"1monthafter","1monthafter","1monthafter","1monthafter",
"1monthafter","1monthafter","1monthafter",
"1monthafter","1monthafter")),
student = as.factor(c("A","B","C","D","E",
"F","G","H","I","J","A","B","C","D","E",
"F","G","H","I","J","A","B","C","D","E","F",
"G","H","I","J","A","B","C","D","E","F",
"G","H","I","J"))
)

Thanks.

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

2 Likes

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.