2016-04-18 4 views
0

私はintersectコマンドを使用したいが、2つの行に2つの "NA"があるので、動作しない。私は「NA」は、行の末尾に表示されるようにG2をソートしたいNA(または同じ値)とのintersectコマンド

A<-matrix(c(4,9,5,3,1,7,NA,15,NA,6,9,3,9,5,1,11,3,8,NA,9,7,NA,21,17),4,6,byrow=TRUE) 
B<-matrix(c(7,1,5,9,4,3,NA,NA,6,3,9,15,8,3,11,1,5,9,9,NA,7,NA,17,21),4,6,byrow=TRUE) 
order.A <- t(apply(A, 1, order)) 
A.new <- matrix(A[cbind(c(row(A)), c(order.A))], ,6) 
G1<-matrix(nrow=4,ncol=3) 
G2<-matrix(nrow=4,ncol=3) 
for (i in 1:4){ 
G1[i,]<-intersect(B[i,],A.new[i,1:3]) 
G2[i,]<-intersect(B[i,],A.new[i,4:6]) 
} 


はここに私の試みであることは、次のようになります。

 G1   G2 
(1 4 3)  (7 5 9) 
(6 3 9) (15 NA NA) 
(3 1 5) (8 11 9) 
(9 7 17) (21 NA NA) 
+0

'G2'(= dput(G2)の結果を投稿したいかもしれません)の入力とそれに対応する出力は何ですか? G2 [i、] < - intersect(B [i、]、A.new [i、4:6])のエラー: 置き換えられる項目の数が倍数ではありません交叉(B [4、]、A.new [4,4:6])はあなたのデータでは機能しません。 – lukeA

+0

はい、NAのためにintersectコマンドが機能しません。 "na.rm"や "NA = T"のような追加のコマンドがあるかもしれないので、RはNAを無視するか、行の最後に置くようにしますか? – Jordan

+0

intersectコマンドは動作します: 'intersect(A.new [4、4:6]、B [4、])'。完璧な交差の世界では、その命令の結果はどうあるべきですか? '\' length < - \ '(交叉(A.new [4、4:6]、B [4、])、3)'? – lukeA

答えて

0

あなたは

を行うことができます
A<-matrix(c(4,9,5,3,1,7, NA,15,NA,6,9,3, 9,5,1,11,3,8, NA,9,7,NA,21,17),4,6,byrow=TRUE) 
B<-matrix(c(7,1,5,9,4,3, NA,NA,6,3,9,15, 8,3,11,1,5,9, 9,NA,7,NA,17,21),4,6,byrow=TRUE) 
order.A <- t(apply(A, 1, order)) 
A.new <- matrix(A[cbind(c(row(A)), c(order.A))], ,6) 
G1<-matrix(nrow=4,ncol=3) 
G2<-matrix(nrow=4,ncol=3) 
for (i in 1:4){ 
    G1[i,]<-intersect(B[i,],A.new[i,1:3]) 
    G2[i,]<-`length<-`(intersect(A.new[i, 4:6], B[i, ]), 3) 
} 
G2 
#  [,1] [,2] [,3] 
# [1,] 5 7 9 
# [2,] 15 NA NA 
# [3,] 8 9 11 
# [4,] 21 NA NA 

intersectコマンドの結果の長さが<3の場合、バリエーションはさらにNA秒になります。

関連する問題