2017-11-25 116 views
0

我正在努力尋找一些真正容易理解的東西,但我無法解決我的R技巧。在矩陣[,, i]中查找NAs,並在矩陣中將它們的位置標記爲NA

讓我們假設我有以下數組:

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,我需要轉換爲NA是NA兩個my_array[,,i]方面的意見,其中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

你有什麼建議嗎? 感謝

回答

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 
+0

我真正的陣列已經得到了I = 1 :1000。我無法應用你的解決方案 – aaaaa

+1

,所以你可以使用這個代碼:'mat3 [which(apply(is.na(my_array),FUN = prod,MARGIN = 1:1000)== 1,arr.ind = TRUE,useNames = FALSE)] = NA' –

+0

嗨,它不適用於i = 1:1000。我得到了以下錯誤:錯誤在if(d2 == 0L){:缺少值,其中TRUE/FALSE需要 – aaaaa