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)
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With