[R] convert a data frame to matrix - changed column name

Muhammad Subianto msubianto at gmail.com
Thu Apr 6 16:16:52 CEST 2006


I have a question, which very easy to solve, but I can't find a solution.
I want to convert a data frame to matrix. Here my toy example:

> L3 <- c(1:3)
> L10 <- c(1:6)
> d <- data.frame(cbind(x=c(10,20), y=L10), fac=sample(L3, + 6, repl=TRUE))
> d
   x y fac
1 10 1   1
2 20 2   1
3 10 3   1
4 20 4   3
5 10 5   2
6 20 6   2
> is.data.frame(d)
[1] TRUE
> sapply(d, function(x) unlist(x, use.names=FALSE))
      x y fac
[1,] 10 1   1
[2,] 20 2   1
[3,] 10 3   1
[4,] 20 4   3
[5,] 10 5   2
[6,] 20 6   2
> is.matrix(sapply(d, function(x) unlist(x, use.names=FALSE)))
[1] TRUE
>

Yes, I get a matrix TRUE. But I need to change a column name like [,1]
[,2] [,3]. I need the result like

     [,1] [,2] [,3]
[1,]   10    1    1
[2,]   20    2    1
[3,]   10    3    1
[4,]   20    4    3
[5,]   10    5    2
[6,]   20    6    2

How can I do that?
Thanks in advance, Muhammad Subianto




More information about the R-help mailing list