我想使用intersect命令,但我有两次" 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进行排序,以便&#34; NA&#34;出现在行的末尾:它应该如下所示:
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 :(得分: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
如果NA
命令的结果长度为intersect
,则变体将填充额外的<3
s。