R - 用 NA 替换矩阵*仅一行*中的零值
R - replacing the zero values in *just one row* of a matrix with NA
矩阵 A
第一行有一些 0 和 1。
A <- matrix(data=c( 0,0,1,1,0,0,0,1,0, #1
0,0,0,0,1,0,0,0,0, #2
1,0,0,0,0,0,0,0,0, #3
1,0,0,0,0,0,0,0,1, #4
0,1,0,0,0,1,0,0,0, #5
0,0,0,0,1,0,0,0,0, #6
0,0,0,0,0,0,0,0,0, #7
1,0,0,0,0,0,0,0,0, #8
0,0,0,1,0,0,0,0,0 ),#9
nrow=9, ncol=9)
我只需要用 NA
值替换 这一行 中的零。 result
应如下所示:
result <- matrix(data=c( NA,NA,1,1,NA,NA,NA,1,NA, #1
0,0,0,0,1,0,0,0,0, #2
1,0,0,0,0,0,0,0,0, #3
1,0,0,0,0,0,0,0,1, #4
0,1,0,0,0,1,0,0,0, #5
0,0,0,0,1,0,0,0,0, #6
0,0,0,0,0,0,0,0,0, #7
1,0,0,0,0,0,0,0,0, #8
0,0,0,1,0,0,0,0,0 ),#9
nrow=9, ncol=9)
Other solutions to similar problems 将整个矩阵中的给定值完全替换为另一个值不适用,令我惊讶的是我未能扩展这些解决方案。
A[1, A[1,] == 0] <- NA
A
# [,1] [,2] [,3] [,4] [,5] [,6] [,7] [,8] [,9]
# [1,] NA NA 1 1 NA NA NA 1 NA
# [2,] 0 0 0 0 1 0 0 0 0
# [3,] 1 0 0 0 0 0 0 0 0
# [4,] 1 0 0 0 0 0 0 0 1
# [5,] 0 1 0 0 0 1 0 0 0
# [6,] 0 0 0 0 1 0 0 0 0
# [7,] 0 0 0 0 0 0 0 0 0
# [8,] 1 0 0 0 0 0 0 0 0
# [9,] 0 0 0 1 0 0 0 0 0
矩阵 A
第一行有一些 0 和 1。
A <- matrix(data=c( 0,0,1,1,0,0,0,1,0, #1
0,0,0,0,1,0,0,0,0, #2
1,0,0,0,0,0,0,0,0, #3
1,0,0,0,0,0,0,0,1, #4
0,1,0,0,0,1,0,0,0, #5
0,0,0,0,1,0,0,0,0, #6
0,0,0,0,0,0,0,0,0, #7
1,0,0,0,0,0,0,0,0, #8
0,0,0,1,0,0,0,0,0 ),#9
nrow=9, ncol=9)
我只需要用 NA
值替换 这一行 中的零。 result
应如下所示:
result <- matrix(data=c( NA,NA,1,1,NA,NA,NA,1,NA, #1
0,0,0,0,1,0,0,0,0, #2
1,0,0,0,0,0,0,0,0, #3
1,0,0,0,0,0,0,0,1, #4
0,1,0,0,0,1,0,0,0, #5
0,0,0,0,1,0,0,0,0, #6
0,0,0,0,0,0,0,0,0, #7
1,0,0,0,0,0,0,0,0, #8
0,0,0,1,0,0,0,0,0 ),#9
nrow=9, ncol=9)
Other solutions to similar problems 将整个矩阵中的给定值完全替换为另一个值不适用,令我惊讶的是我未能扩展这些解决方案。
A[1, A[1,] == 0] <- NA
A
# [,1] [,2] [,3] [,4] [,5] [,6] [,7] [,8] [,9]
# [1,] NA NA 1 1 NA NA NA 1 NA
# [2,] 0 0 0 0 1 0 0 0 0
# [3,] 1 0 0 0 0 0 0 0 0
# [4,] 1 0 0 0 0 0 0 0 1
# [5,] 0 1 0 0 0 1 0 0 0
# [6,] 0 0 0 0 1 0 0 0 0
# [7,] 0 0 0 0 0 0 0 0 0
# [8,] 1 0 0 0 0 0 0 0 0
# [9,] 0 0 0 1 0 0 0 0 0