[R] matrix subsetting assignment with logical mask

2009-07-16 Thread Ross Boylan
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,]147
[2,]258
[3,]369
> ifelse(s, x, 0) # x[s] <- 0
 [,1] [,2] [,3]
[1,]100
[2,]258
[3,]309

Is there a better way?

Ross Boylan

__
R-help@r-project.org mailing list
https://stat.ethz.ch/mailman/listinfo/r-help
PLEASE do read the posting guide http://www.R-project.org/posting-guide.html
and provide commented, minimal, self-contained, reproducible code.


Re: [R] matrix subsetting assignment with logical mask

2009-07-16 Thread David Winsemius


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,]147
[2,]258
[3,]369

ifelse(s, x, 0) # x[s] <- 0

[,1] [,2] [,3]
[1,]100
[2,]258
[3,]309

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,]047
[2,]000
[3,]060

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,]   2147
[2,]   22   25   28
[3,]   236   29

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

__
R-help@r-project.org mailing list
https://stat.ethz.ch/mailman/listinfo/r-help
PLEASE do read the posting guide http://www.R-project.org/posting-guide.html
and provide commented, minimal, self-contained, reproducible code.