Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In R, match function for rows or columns of matrix

Tags:

r

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!')   
}
like image 808
Causality Avatar asked Oct 02 '12 19:10

Causality


1 Answers

match will work on lists 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.

like image 72
Matthew Plourde Avatar answered Nov 03 '22 23:11

Matthew Plourde