[R] respecting original matrix dimensions

Marc Schwartz marc_schwartz at me.com
Tue Apr 6 13:44:09 CEST 2010


On Apr 6, 2010, at 6:39 AM, Robert M. Flight wrote:

> Hi All,
> 
> I'm hoping someone else can help me out with this. I am doing some
> matrix algebra using sub-parts of matrices, and sometimes I need only
> a single row/column of the original matrix. However, whenever I pull
> out only a single row/column, R returns a row vector, but often this
> will break my matrix algebra. Is there any *easy* way to get R to
> remember what the single row/column came out of and format the return
> appropriately?
> 
> Example:
> 
> crud <- matrix(c(1,2,3,4,5,6,7,8,9,10,11,12),nrow=3,ncol=4)
> tmp <- crud[,1]
> #tmp gives:  [1] 1 2 3
> 
> what I actually want is:
> tmp <- crud[,1]
> #tmp gives
>     [,1]
> [1,]    1
> [2,]    2
> [3,]    3
> 
> I don't see an easy way to do this beyond using matrix and supplying
> the correct matrix dimensions based on the indexing, or using a
> conditional to check if only one column/row is being taken out.
> 
> Any help would be very much appreciated.
> 
> Regards,
> 
> -Robert


See R FAQ 7.5:

  http://cran.r-project.org/doc/FAQ/R-FAQ.html#Why-do-my-matrices-lose-dimensions_003f

HTH,

Marc Schwartz



More information about the R-help mailing list