[R] logical masking of a matrix converts it to a vector
David Winsemius
dwinsemius at comcast.net
Fri Dec 4 22:00:30 CET 2009
On Dec 4, 2009, at 3:52 PM, Austin Huang wrote:
> One problem I've been having is the special case in which only one
> row/column remains and the variable gets converted into a vector when
> entries are removed by logical masking. This is a problem because
> subsequent
> code may rely on matrix operations (apply, colsums, dim, etc) For
> example:
>
>> a <- matrix(c(1, 2, 3, 4), nrow = 2)
>> a
> [,1] [,2]
> [1,] 1 3
> [2,] 2 4
>> rmask <- c(TRUE, FALSE)
>> b <- a[rmask, ]
>> colSums(b)
> b <- a[rmask, , drop=FALSE]
> colSums(b)
[1] 1 3
> Error in colSums(b) : 'x' must be an array of at least two dimensions
>
> To ensure the code works regardless of how the matrix gets modified,
> I need
> to explicitly recast results to a matrix, for example:
>
> b <- matrix(a[rmask, ], ncol = 2)
>
> This can get messy, requiring extra work to maintain column/row
> names or
> additional commands to determine the correct dimensions of the
> matrix (for
> example, if I'm masking both rows and columns simultaneously). Is
> there a
> more elegant way to deal with this in R?
--
David Winsemius, MD
Heritage Laboratories
West Hartford, CT
More information about the R-help
mailing list