Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get index of data.table column that matches a value

DT = data.table(
      id = 1:5,
      a  = c(0,1,0,2,5),
      b  = c(1,0,2,4,4),
      c  = c(1,2,0,0,5))

#     id a b c
# 1:  1  0 1 1
# 2:  2  1 0 2
# 3:  3  0 2 0
# 4:  4  2 4 0
# 5:  5  5 4 5

I want to identify the first column from the left which has 0, and put the column index in idx.

#     id a b c idx
# 1:  1  0 1 1 2 
# 2:  2  1 0 2 3
# 3:  3  0 2 0 2
# 4:  4  2 4 0 4
# 5:  5  5 4 5 NA

(Non-data.table solutions, e.g., with dplyr are also welcome)

like image 699
Orion Avatar asked Sep 16 '25 07:09

Orion


1 Answers

An idea via base R can be,

replace(max.col(-DT[, -1] == 0, ties.method = 'first') + 1, rowSums(DT == 0) == 0, NA)

#or break it into two lines If you want,
i1 <- max.col(-DT[,-1] == 0, ties.method = 'first') + 1
replace(i1, rowSums(DT == 0) == 0, NA)

#[1]  2  3  2  4 NA
like image 169
Sotos Avatar answered Sep 17 '25 21:09

Sotos