该值匹配函数中R是非常有用的.但根据我的理解,它不足以支持两个或高维输入.
例如,假设x和y是相同数量的列的矩阵,我想匹配行的x行y.'R'函数调用match(x,y)不会这样做.列表的输入也出现相同的不足.
我已经实现了我自己的版本调用matchMat(xMat, yMat)(附在下面),但我想知道你是什么解决了这个任务.
matchMat = function(xMat, uMat, dimn=1) {
ind = rep(-1, dim(xMat)[dimn])
id = 1 : dim(uMat)[dimn]
for (i in id) {
e = utilSubMat(i, uMat, dimn)
isMatch = matchVect(e, xMat, dimn)
ind[isMatch] = i
}
return(ind)
}
matchVect = function(v, xMat, dimn) {
apply(xMat, dimn, function(e) {
tf = e == v
all(tf)
})
}
unittest_matchMat = function() {
dimn = 1
uMat = matrix(c(1, 2, 2, 3, 3, 4, 4, 5), ncol=2, byrow=T)
ind = sample(dim(uMat)[1], 10, replace=T)
print(ind)
xMat = uMat[ind, ]
rst = matchMat(xMat, uMat, dimn)
print(rst)
stopifnot(all(ind == rst))
xMat2 = rbind(c(999, 999), xMat, c(888, 888))
rst2 = matchMat(xMat2, uMat, dimn)
print(rst2)
stopifnot(all(c(-1, ind, -1) == rst2))
print('pass!')
}
Run Code Online (Sandbox Code Playgroud)
Mat*_*rde 13
match将list研究原子载体.因此,要将一个矩阵的行匹配到另一个矩阵,您可以:
match(data.frame(t(x)), data.frame(t(y)))
Run Code Online (Sandbox Code Playgroud)
t将行转换为列,然后在转置矩阵中data.frame创建一list列.
row.match包中的函数prodlim允许您识别一个矩阵中在另一个矩阵中也找到(相同)的行。非常方便且易于使用。
library(prodlim)
row.match(x,y)
Run Code Online (Sandbox Code Playgroud)