[R] matrix subsetting assignment with logical mask
Ross Boylan
ross at biostat.ucsf.edu
Fri Jul 17 00:41:55 CEST 2009
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?
Ross Boylan
More information about the R-help
mailing list