返回矩阵列索引匹配R中的值

时间:2016-06-29 09:50:02

标签: r matrix match

我正在寻找一种快速方法来返回矩阵的列索引,这些索引与向量中提供的值匹配(理想情况下长度为1或与矩阵中的行数相同) 例如:

mat <- matrix(1:100,10)  
values <- c(11,2,23,12,35,6,97,3,9,10)

我称之为rowMatches()的所需函数将返回:

rowMatches(mat, values)
 [1]  2  1  3 NA  4  1 10 NA  1  1

实际上,值11首先在第一行的第2列找到,值2出现在第2行的第1列,值23出现在第3行的第3列,值12不在第4行行...等等。

由于我没有在包matrixStats中找到任何解决方案,我想出了这个功能:

rowMatches <- function(mat,values) {            
    res <- integer(nrow(mat))
    matches <- mat == values
    for (col in ncol(mat):1) {
        res[matches[,col]] <- col
    }
    res[res==0] <- NA
    res
}

对于我的预期用途,将有数百万行和几列。因此,将矩阵拆分为行(在名为rows的列表中)并调用Map(match, as.list(values), rows)将会太慢。 但我对我的功能并不满意,因为有一个循环,如果有很多列可能会很慢。应该可以在列上使用apply(),但不会使它更快。

有什么想法吗?

2 个答案:

答案 0 :(得分:1)

res <- arrayInd(match(values, mat), .dim = dim(mat))
res[res[, 1] != seq_len(nrow(res)), 2] <- NA
#      [,1] [,2]
# [1,]    1    2
# [2,]    2    1
# [3,]    3    3
# [4,]    2   NA
# [5,]    5    4
# [6,]    6    1
# [7,]    7   10
# [8,]    3   NA
# [9,]    9    1
#[10,]   10    1

答案 1 :(得分:0)

罗兰的答案很好,但我会发布另一种解决方案:

res <- which(mat==values, arr.ind = T)
res <- res[match(seq_len(nrow(mat)), res[,1]), 2]