与 NA(或相同值)相交的命令

intersect command with NA (or same values)

我想使用相交命令,但是我在两行中有两次"NA",所以它不起作用。
这是我的尝试:

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])
}

我想对 G2 进行排序,使 "NA" 出现在行的末尾:它应该如下所示:

      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) 

你可以做到

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,则变体将填充额外的 NAs。