简体   繁体   中英

R: Replace elements with NA in a matrix in corresponding positions to NA's in another matrix

I have a large matrix, z, that I removed all values >3 and replaced with NA using:

z[z>3]<-NA

I have another matrix, y , of identical dimensions that I need to replace values with NA in positions corresponding to the locations where the elements were replaced in element z. That is, if z[3,12] was >3 and replaced with NA, I need y[3,12] to be replaced with NA too. They have the same row names if that helps.

Just use is.na on the first matrix to select the values to replace in the second matrix.

Example:

set.seed(1)

m1 <- matrix(sample(5, 25, TRUE), 5)
m2 <- matrix(sample(5, 25, TRUE), 5)

m1[m1 > 3] <- NA
m2[is.na(m1)] <- NA
m2
#      [,1] [,2] [,3] [,4] [,5]
# [1,]    2   NA    4    5   NA
# [2,]    1   NA    4   NA    1
# [3,]    2   NA   NA   NA   NA
# [4,]   NA   NA    4    3    4
# [5,]    2    5   NA   NA    4
set.seed(42)
z <- matrix(rnorm(15, mean = 1), nrow = 5)
y <- matrix(0, nrow = 5, ncol = 3)

z
#           [,1]      [,2]       [,3]
# [1,] 2.3709584 0.8938755  2.3048697
# [2,] 0.4353018 2.5115220  3.2866454
# [3,] 1.3631284 0.9053410 -0.3888607
# [4,] 1.6328626 3.0184237  0.7212112
# [5,] 1.4042683 0.9372859  0.8666787
y
#      [,1] [,2] [,3]
# [1,]    0    0    0
# [2,]    0    0    0
# [3,]    0    0    0
# [4,]    0    0    0
# [5,]    0    0    0

# The 2D matrix can be indexed as a vector
idx <- which(z > 3)

z[idx] <- NA
y[idx] <- NA

z
#           [,1]      [,2]       [,3]
# [1,] 2.3709584 0.8938755  2.3048697
# [2,] 0.4353018 2.5115220         NA
# [3,] 1.3631284 0.9053410 -0.3888607
# [4,] 1.6328626        NA  0.7212112
# [5,] 1.4042683 0.9372859  0.8666787
y
#      [,1] [,2] [,3]
# [1,]    0    0    0
# [2,]    0    0   NA
# [3,]    0    0    0
# [4,]    0   NA    0
# [5,]    0    0    0

How about:

is.na(y) <- is.na(z) <- z < 3 & !is.na(z)

or simply

is.na(y) <- is.na(z) <- z < 3

if z is guaranteed not to have missing values prior to the assignment

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM