有效地找到数据表的第一个非零元素(对应列) [英] efficiently finding first nonzero element (corresponding column) of a data table
问题描述
关于以下类型的问题,有一些答案,但它们都效率低下,并且扩展性不佳。
There are some answers on stack to the below type of question, but they are all inefficient and do not scale well.
要重现它,假设我有如下数据:
To reproduce it, suppose I have data that looks like this:
tempmat=matrix(c(1,1,0,4,1,0,0,4,0,1,0,4, 0,1,1,4, 0,1,0,5),5,4,byrow=T)
tempmat=rbind(rep(0,4),tempmat)
tempmat=data.table(tempmat)
names(tempmat)=paste0('prod1vint',1:4)
这是数据的样子,尽管它要大得多,所以解决方案不能是应用或基于行的方法。
This is what the data look like, although it is MUCH bigger, so the solution cannot be an "apply" or row-wise based approach.
> tempmat
prod1vint1 prod1vint2 prod1vint3 prod1vint4
1: 0 0 0 0
2: 1 1 0 4
3: 1 0 0 4
4: 0 1 0 4
5: 0 1 1 4
6: 0 1 0 5
我想要来标识第一个非零元素的列,因此输出将如下所示:
I want to identify the column of the first nonzero element, so the output would look like this:
> tempmat
prod1vint1 prod1vint2 prod1vint3 prod1vint4 firstnonzero
1: 0 0 0 0 NA
2: 1 1 0 4 1
3: 1 0 0 4 1
4: 0 1 0 4 2
5: 0 1 1 4 2
6: 0 1 0 5 2
推荐答案
一种选择是使用 rowSums
和 max.col
指定 ties.method = first
One option is to use rowSums
with max.col
specifying ties.method = "first"
temp <- tempmat != 0
(NA^(rowSums(temp) == 0)) * max.col(temp, ties.method = "first")
#[1] NA 1 1 2 2 2
max.col
将给出列索引为每行的第一个最大值。但是,如果所有值均为0(如第1行),则返回1,因为0是该行的最大值。为避免这种情况,我们使用 rowSums
检查行中是否至少有一个非零值,并将其乘以 max.col
输出。
max.col
would give column index of first maximum value in every row. However, this would return 1 in case all the values are 0 (like in 1st row) since 0 is the maximum value in the row. To avoid that we check if there is at least one non-zero value in the row using rowSums
and multiply it to max.col
output.
这篇关于有效地找到数据表的第一个非零元素(对应列)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!