Skip to content

Converting a matrix to a dataframe: how to prevent conversion to factor

2 messages · Dennis Fisher, Peter Dalgaard

#
Dennis Fisher <fisher at plessthan.com> writes:
I don't think that is going to help.... 

There are really several issues here: Your numeric column was
converted to character by the cbind, using as.data.frame(I(MATRIX))
will not split it into individual columns, and things like
apply(MATRIX,2,f) may do the right thing to begin with, but then
there's coercion due to an implicit cbind at the end.

It's a bit awkward, but this may do it:
`data.frame':   4 obs. of  2 variables:
 $ TEXT   : Factor w/ 4 levels "Text1","Text2",..: 1 2 3 4
 $ NUMBERS: int  14 13 12 11

whereas this isn't right:
int [1:4, 1:2] 1 2 3 4 14 13 12 11
 - attr(*, "dimnames")=List of 2
  ..$ : NULL
  ..$ : chr [1:2] "TEXT" "NUMBERS"