[R] matrix subsetting assignment with logical mask

David Winsemius dwinsemius at comcast.net
Fri Jul 17 01:13:55 CEST 2009


On Jul 16, 2009, at 6:41 PM, Ross Boylan wrote:

> If m is a matrix and s is a logical matrix of the same dimensions, I'd
> like to be able to update m with
> m[s] <- 0
> If m2 is another matrix, I'd also like to be able to do
> m[s] <- m2
> where elements of m for which s is TRUE get the corresponding  
> element of
> m2.
>
> However, this doesn't work in R 2.7.1.  The best I've been able to  
> come
> up with is
>> s
>     [,1]  [,2]  [,3]
> [1,] TRUE FALSE FALSE
> [2,] TRUE  TRUE  TRUE
> [3,] TRUE FALSE  TRUE
>> x
>     [,1] [,2] [,3]
> [1,]    1    4    7
> [2,]    2    5    8
> [3,]    3    6    9
>> ifelse(s, x, 0) # x[s] <- 0
>     [,1] [,2] [,3]
> [1,]    1    0    0
> [2,]    2    5    8
> [3,]    3    0    9
>
> Is there a better way?

Upgrade? .... your hoped-for "better way" works in 2.9.1

 > X <- matrix(1:9, ncol=3)
 > s <- matrix(c(T,T,T,FALSE,T,FALSE,FALSE,T,T),nrow=3)
 > X[s] <- 0
 > X
      [,1] [,2] [,3]
[1,]    0    4    7
[2,]    0    0    0
[3,]    0    6    0

You _are_ asked to upgrade before posting.

And the analogous method for "works" for substituting from a third  
matrix:
 > M2 <- matrix(21:29, nrow=3)
 > X[s] <- M2[s]
 > X
      [,1] [,2] [,3]
[1,]   21    4    7
[2,]   22   25   28
[3,]   23    6   29

--
David Winsemius, MD
Heritage Laboratories
West Hartford, CT




More information about the R-help mailing list