[R] why it returns list level number instead of its content?
Richard M. Heiberger
rmh at temple.edu
Tue Oct 24 07:14:48 CEST 2006
The class "factor" is defined for vectors, not matrices.
The attempt to use a factor in a matrix setting coerces it to numeric.
See the documentation for factor where it says
"In particular, as.numeric applied to a factor is meaningless,
and may happen by implicit coercion."
> tmp <- matrix(1:8, 4)
> tmp
[,1] [,2]
[1,] 1 5
[2,] 2 6
[3,] 3 7
[4,] 4 8
> factor(tmp)
[1] 1 2 3 4 5 6 7 8
Levels: 1 2 3 4 5 6 7 8
>
## A simplified example based on yours:
> tmp <- data.frame(a=factor(letters[1:4]), b=factor(letters[5:8]))
> tmp
a b
1 a e
2 b f
3 c g
4 d h
> cbind(tmp$a, tmp$b) ## coerced to numeric, both factors went to 1:4
[,1] [,2]
[1,] 1 1
[2,] 2 2
[3,] 3 3
[4,] 4 4
> tmp[, c("a","b")] ## in your example, subscripting is probably the right method
a b
1 a e
2 b f
3 c g
4 d h
> cbind.data.frame(tmp$a, tmp$b) ## explicit use of cbind.data.frame works.
tmp$a tmp$b
1 a e
2 b f
3 c g
4 d h
Rich
More information about the R-help
mailing list