m0h3n - 1 year ago 71
R Question

# Extract the first TRUE per row in logical matrix efficiently in R

Given the following matrix:

``````         A     B    C
[1,]  TRUE FALSE TRUE
[2,] FALSE  TRUE TRUE
[3,] FALSE FALSE TRUE
[4,] FALSE  TRUE TRUE
[5,] FALSE  TRUE TRUE
[6,]  TRUE  TRUE TRUE

m <- structure(c(TRUE, FALSE, FALSE, FALSE, FALSE, TRUE, FALSE, TRUE,
FALSE, TRUE, TRUE, TRUE, TRUE, TRUE, TRUE, TRUE, TRUE, TRUE), .Dim = c(6L,
3L), .Dimnames = list(NULL, c("A", "B", "C")))
``````

How we can extract the first column with TRUE value per row efficienly? Of course, we could use
`apply`
per row and then get the
`min(which(...))`
.

Here is the desired output:

``````[1] A B C B B A
``````

We can use `max.col`

``````colnames(m)[max.col(m, "first")]
#[1] "A" "B" "C" "B" "B" "A"
``````

If there are no TRUE in a row, then we can change it to `NA` (if needed)

``````colnames(m)[max.col(m, "first")*NA^!rowSums(m)]
``````

Or with `ifelse`

``````colnames(m)[ifelse(rowSums(m)==0, NA, max.col(m, "first"))]
``````
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download