Wednesday, June 18, 2008

R: keeping a 1-d subset of a matrix a matrix

By default, if a subsetting operations yields a one-dimensional matrix (row or column vector), the dimensions are dropped.
> (m <- matrix(1:4, nrow=2))
[,1] [,2]
[1,] 1 3
[2,] 2 4
> (v <- m[1, 1:2])
[1] 1 3
This can cause problems when we want to go ahead and continue using the result in matrix operations:
> v %*% m %*% t(v)
Error in v %*% m %*% t(v) : non-conformable arguments


The solution is to explicitly tell R not to drop the dimensions:
> (v <- m[1, 1:2, drop=FALSE])
[,1] [,2]
[1,] 1 3
> v %*% m %*% t(v)
[,1]
[1,] 52


Something else to look at: removing a column, given its name in a variable: Chris Handorf, subsetting a dataframe

No comments: