我正在努力学习一些非常容易理解的东西,但我无法解决我的R技能。
假设我有以下数组:
mat1 = as.matrix(data.frame(col1 = c(1,2,3,4,5,6,7,8), col2 = c(2,3,'NA',5,6,7,8,9), col3 = c(3,4,5,6,7,8,9,10), col4 = c(2,3,4,1,2,6,7,8),
col5 = c(2,3,'NA','NA',6,7,8,9), col6 = c(1,2,3,5,6,7,8,9), col7 = c(1,2,3,4,6,7,'NA','NA'), col8 = c(1,2,3,4,5,6,'NA','NA')))
mat2 = as.matrix(data.frame(col1 = c('NA',2,3,4,5,6,7,8), col2 = c(2,3,1,5,6,7,8,9), col3 = c(3,4,5,6,7,8,9,'NA'), col4 = c(2,3,4,1,2,6,7,8),
col5 = c(2,3,11,88,6,7,8,9), col6 = c(1,2,3,5,6,7,8,9), col7 = c(1,2,3,4,6,7,'NA','NA'), col8 = c(1,2,3,4,5,6,'NA','NA')))
#ignore warnings
class(mat1) = 'numeric'
class(mat2) = 'numeric'
my_array = array(c(mat1, mat2), dim = c(8,8,2))
print(my_array)
, , 1
[,1] [,2] [,3] [,4] [,5] [,6] [,7] [,8]
[1,] 1 2 3 2 2 1 1 1
[2,] 2 3 4 3 3 2 2 2
[3,] 3 NA 5 4 NA 3 3 3
[4,] 4 5 6 1 NA 5 4 4
[5,] 5 6 7 2 6 6 6 5
[6,] 6 7 8 6 7 7 7 6
[7,] 7 8 9 7 8 8 NA NA
[8,] 8 9 10 8 9 9 NA NA
, , 2
[,1] [,2] [,3] [,4] [,5] [,6] [,7] [,8]
[1,] NA 2 3 2 2 1 1 1
[2,] 2 3 4 3 3 2 2 2
[3,] 3 1 5 4 11 3 3 3
[4,] 4 5 6 1 88 5 4 4
[5,] 5 6 7 2 6 6 6 5
[6,] 6 7 8 6 7 7 7 6
[7,] 7 8 9 7 8 8 NA NA
[8,] 8 9 NA 8 9 9 NA NA
以下矩阵:
mat3 = matrix(seq(1,64,1), nrow = 8, ncol = 8)
print(mat3)
[,1] [,2] [,3] [,4] [,5] [,6] [,7] [,8]
[1,] 1 9 17 25 33 41 49 57
[2,] 2 10 18 26 34 42 50 58
[3,] 3 11 19 27 35 43 51 59
[4,] 4 12 20 28 36 44 52 60
[5,] 5 13 21 29 37 45 53 61
[6,] 6 14 22 30 38 46 54 62
[7,] 7 15 23 31 39 47 55 63
[8,] 8 16 24 32 40 48 56 64
在mat3
中,我需要将my_array[,,i]
维度中的NA观察值转换为NA,其中i = 1,2
。
我的预期输出是:
[,1] [,2] [,3] [,4] [,5] [,6] [,7] [,8]
[1,] 1 9 17 25 33 41 49 57
[2,] 2 10 18 26 34 42 50 58
[3,] 3 11 19 27 35 43 51 59
[4,] 4 12 20 28 36 44 52 60
[5,] 5 13 21 29 37 45 53 61
[6,] 6 14 22 30 38 46 54 62
[7,] 7 15 23 31 39 47 NA NA
[8,] 8 16 24 32 40 48 NA NA
我的真实数组已经i = 1:1000
。
你有什么建议吗? 感谢
答案 0 :(得分:1)
使用它:
mat3[which(is.na(mat1)*is.na(mat2)==1,arr.ind = TRUE,useNames = FALSE)]=NA
或者这个:
mat3[which(is.na(my_array[,,2])*is.na(my_array[,,1])==1,arr.ind = TRUE,useNames = FALSE)]=NA
1到1000维度:
mat3[which(apply(is.na(my_array),FUN = prod,MARGIN = 1:2)==1,arr.ind = TRUE,useNames = FALSE)]=NA