[R] Making multiple columns to a single column

David Winsemius dwinsemius at comcast.net
Sun Mar 14 00:54:08 CET 2010


On Mar 13, 2010, at 6:30 PM, Hyo Lee wrote:

> Hi guys,
>
> I have a very simple question.
> I'm trying to make multiple columns to a single column.
>
> For example,
>
> *ttx1* is a 46*72 matrix.
>
> so, I tried this.
>
> *d1=ttx1[,1]
> d2=ttx1[,2]
> ...
> d72=ttx1[,72]*
>
> now, d1, d2, ...,d72 become a 46*1 matrix.
> And then.. I tried..
>
> *dd=rbind(d1, d2, ..., d72)*
>
> I thought *dd* should be 3312*1 matrix; but it becomes 72*46.
> I really wanted to make it a  single column (3312*1).
 > ttx1 <- matrix(1:3312, ncol=46)

 > str(ttx1)
  int [1:72, 1:46] 1 2 3 4 5 6 7 8 9 10 .

It is as easy as applying the c() function:

 > str( c(ttx1) )
  int [1:3312] 1 2 3 4 5 6 7 8 9 10 ...

Well maybe only a vector. (as.vector would have done the same thing,  
or if you really want a one column matrix then ...)

 > dim(ttx1) <- c(3312,1)
 > str(ttx1)
  int [1:3312, 1] 1 2 3 4 5 6 7 8 9 10 ...


Matrices in R are basically vectors anyway. Their dim attributes let  
matrix like operations get done but they remain vactors underneath.



>
> Do you know what is wrong in this code?

This code gave you a vector rather than a one column matrix: d1=ttx1[, 
1], since dimensions that are 1 get dropped by default. The only way  
to keep the result as a column matrix would be to use the drop=FALSE  
argument to "[":

 > d1=ttx1[,1, drop=FALSE]
 > d2=ttx1[,2, drop=FALSE]
 > str(rbind(d1,d2))
  int [1:144, 1] 1 2 3 4 5 6 7 8 9 10 ...



> Or, do you have a better idea in
> making multiple columns to a single column?

David Winsemius, MD
West Hartford, CT



More information about the R-help mailing list