简体   繁体   English

R:将矩阵中的NA替换为与另一矩阵中的NA相对应的位置中的NA

[英]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,我删除了所有值> 3并用NA代替:

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. 我有另一个矩阵y ,它具有相同的尺寸,我需要用NA替换值,其位置对应于元素z中元素被替换的位置。 That is, if z[3,12] was >3 and replaced with NA, I need y[3,12] to be replaced with NA too. 也就是说,如果z[3,12] > 3并用NA替换,我也需要y[3,12]用NA替换。 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. 只需在第一个矩阵上使用is.na来选择要在第二个矩阵中替换的值。

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 如果保证z在分配之前没有缺失值

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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