The value matching function in R
is very useful. But from my understanding, it does not sufficiently support two or high dimensional inputs.
For example, assume x
and y
are matrices of same number of columns, and I would like to match rows of x
to rows of y
. The 'R' function call match(x,y)
does not do so. The same insufficiency occurs to inputs of lists.
I have implemented my own version of it called matchMat(xMat, yMat)
(attached below), but I am wondering what is you solution to this task.
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!')
}
match
will work on list
s of atomic vectors. So to match rows of one matrix to another, you could do:
match(data.frame(t(x)), data.frame(t(y)))
t
transposes the rows into columns, then data.frame
creates a list
of the columns in the transposed matrix.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With