在R中,我可以使用匹配函数轻松匹配唯一标识符:
match(c(1,2,3,4),c(2,3,4,1))
# [1] 4 1 2 3
当我尝试匹配非唯一标识符时,我得到以下结果:
match(c(1,2,3,1),c(2,3,1,1))
# [1] 3 1 2 3
有没有办法匹配“无需替换”的索引,也就是说,每个索引只出现一次?
othermatch(c(1,2,3,1),c(2,3,1,1))
# [1] 3 1 2 4 # note the 4 where there was a 3 at the end
答案 0 :(得分:3)
您正在寻找pmatch
pmatch(c(1,2,3,1),c(2,3,1,1))
# [1] 3 1 2 4
答案 1 :(得分:2)
更天真的方法 -
library(data.table)
a <- data.table(p = c(1,2,3,1))
a[,indexa := .I]
b <- data.table(q = c(2,3,1,1))
b[,indexb := .I]
setkey(a,p)
setkey(b,q)
# since they are permutation, therefore cbinding the ordered vectors should return ab with ab[,p] = ab[,q]
ab <- cbind(a,b)
setkey(ab,indexa)
ab[,indexb]
#[1] 3 1 2 4