m0h3n - 9 months ago 34

R Question

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

`apply`

`min(which(...))`

Here is the desired output:

`[1] A B C B B A`

Answer

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"))]
```

Source (Stackoverflow)