[R] can I have a matrix of factors, please?

Liaw, Andy andy_liaw at merck.com
Mon Sep 29 17:38:39 CEST 2003


Dear R-help,

Is it a violation of the S language to have a matrix of factors?  What I
would like to have is just a factor object that has dim attribute, and can
be printed (and subsetted) like a matrix; i.e., all columns/rows have the
identical levels.  However, I can't get it to work:

> x <- factor(sample(2, 10, replace=TRUE))
> dim(x)<- c(5,2)
> x
 [1] 1 2 2 1 2 1 1 1 2 1
Levels: 1 2
> str(x)
 int [1:5, 1:2] 1 2 2 1 ...
 - attr(*, "levels")= chr [1:2] "1" "2"
 - attr(*, "class")= chr "factor"
> x[1,]
factor(0)
Levels: 1 2

(This is R 1.7.1 on WinXPPro.)

The alternative is to have a list instead, where each "column" makes up a
component of the list.  But it would be nice to have the matrix...

Best,
Andy
Andy Liaw, PhD
Biometrics Research      PO Box 2000, RY33-300     
Merck Research Labs           Rahway, NJ 07065
mailto:andy_liaw at merck.com        732-594-0820




More information about the R-help mailing list