Supposed I have the following
dt <- data.table(a=c(T,T,F,F), b= c(T,F,T,F))
return,
a b
1: TRUE TRUE
2: TRUE FALSE
3: FALSE TRUE
4: FALSE FALSE
I have tried to use function(x) min(which(x))
to determine the first TRUE
of each row in dt
, but it did not work. The result that I expect will be
a b index
1: TRUE TRUE 1
2: TRUE FALSE 1
3: FALSE TRUE 2
4: FALSE FALSE 9999
,where the index column represents the position of first TRUE
and 9999 is used when that row contains only FALSE
FYI: In the real data, I have around 50 columns that contains TRUE and FALSE
Could you please give me suggestions?
For 50 columns, it is better to use max.col
dt$index <- max.col(dt, 'first') *(!!rowSums(dt))
Or as @David Arenburg mentioned, more idiomatic code would be
dt[, indx := max.col(.SD,ties.method="first")*(!!rowSums(.SD))]
If we need 9999
(max.col(dt)*(!!rowSums(dt))) + (!rowSums(dt))*9999
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