in R, recovering strings that have been converted to factors with factor()

91 views Asked by At

I converted some columns from my dataset into factor levels to conduct analysis. How can I view the definitions of the factor levels which now inhabit my matrix? Are the original names lost? I used the following command on dtafactor, which is a matrix object.

dtafactor[,4:9]=factor(dtafactor[,4:9])
1

There are 1 answers

0
Roland On

Assuming you really have a matrix, the information is lost. The reason is that a matrix can't hold a mixture of variables and can't hold a factor variable. Thus the integers that are the basis of factors (together with the levels attribute) are coerced to a type that fits with the rest of the columns (and the levels are lost), probably to character.

mat <- matrix(letters[1:4], 2)
mat[,2] <- factor(mat[,2])
#    [,1] [,2]
#[1,] "a"  "1" 
#[2,] "b"  "2"

You have to rerun your script up to that point. You probably should use a data.frame instead of a matrix as your data structure.