R-根据每一行的函数获取矩阵的列索引 [英] R - get the column index of a matrix based on a function for each row

查看:104
本文介绍了R-根据每一行的函数获取矩阵的列索引的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

> set.seed(2014)
> m<-matrix(sample(10,16,replace=TRUE),nrow=4)
> m
     [,1] [,2] [,3] [,4]
[1,]    3    6    1    7
[2,]    2    1    2    6
[3,]    7   10    7    7
[4,]    4    7    1    5

对于每一行,我想检索该行中第一个元素的索引,该索引大于或等于最后一个元素,否则返回NA.因此,对于第1行,在前三列中没有元素> = 7,因此应返回NA.对于第3行,第一个元素为> = 7,因此应返回1.

For each row, I'd like to retrieve the index of the first element in that row which is greater than or equal to the last element, and NA otherwise. So, for row 1, there are no elements>=7 in the first three columns, so NA should be returned. For row 3, the first element is >=7 so 1 should be returned.

结果应该是长度为4的向量,等于(NA,NA,1,2)

The result should be a vector of length 4 equal to (NA, NA, 1, 2)

我认为解决方案可能涉及套用,但我不知道如何正确解决.另外,请记住效率,因为我的真实矩阵可能有数百万行.

I thought the solution might involve apply but I couldn't figure out how to get it right. Also, please keep efficiency in mind as my real matrix could have millions of rows.

谢谢

推荐答案

另一种尝试:

apply(m[,-ncol(m)] >= m[,ncol(m)], 1, match, x=TRUE)
#[1] NA NA  1  2

或删除apply:

chk <- m[,-ncol(m)] >= m[,ncol(m)]
replace(max.col(chk,"first"), rowSums(chk)==0, NA)
#[1] NA NA  1  2

它实际上创建了除最后一个列之外的所有m列的逻辑矩阵,测试值是否为最后一个列值的>=.然后,使用match提取每行中第一个TRUE的位置.

It essentially creates a logical matrix of the all the m columns except the last, testing if the values are >= to the last column values. Then the position of the first TRUE in each row is extracted using match.

针对Ben的解决方案使用更大的矩阵进行测试的速度:

Testing speed using a bigger matrix against Ben's solution:

m<-matrix(sample(10,1.6e6,replace=TRUE),nrow=4e5)

replicate(5,
system.time(
 apply(m[,-ncol(m)] >= m[,ncol(m)], 1, match, x=TRUE)
))
#elapsed     0.7 0.77 0.77 0.76 0.93

replicate(5,
system.time({
 m2 <- sweep(m,1,m[,ncol(m)],">=")
 v <- apply(m2,1,function(x) which(x)[1])
 ifelse(v==ncol(m),NA,v)
}))
#elapsed    1.11 1.04 1.10 1.06 1.06

这篇关于R-根据每一行的函数获取矩阵的列索引的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆