Return index of column that has TRUE values

Viewed 685

I am trying to find the number (index) of the column, that has atleast one TRUE value.

library(tidyverse)

df1 <- tibble(a = c(111, 222, 333, 444, 555))

df2 <- tibble(a = c(11, 22, 33, 44, 55), 
              b = c(1111, 2222, 3333, 4444, 5555),
              c = c(11111, 2222, 333, 4444, 55555),
              d = c(1, 2, 3, 4, 5))

find_twin <- function(x){
  df1$a %in% x
}

df_lgl <- as_tibble(sapply(df2, find_twin))
df_lgl 
# A tibble: 5 x 4
  a     b     c     d    
  <lgl> <lgl> <lgl> <lgl>
1 FALSE FALSE FALSE FALSE
2 FALSE FALSE FALSE FALSE
3 FALSE FALSE TRUE  FALSE
4 FALSE FALSE FALSE FALSE
5 FALSE FALSE FALSE FALSE

result
[1] 3

In this case column "c" has a TRUE value, so the result should be a vector with a single 3, since it is the third column. If more columns had TRUE values, then all of those column indexes should be returned in the vector.

I tried:

which(df_lgl == TRUE)

But that gives me a "13" because with that i am asking for the value that's TRUE, not the column number. I have searched online but could not find anything so i think it must be something very easy but i can't find the solution.

Maybe i don't even need to create the function "find_twin". I just need to get the column index or indexes in df2, that has atleast one identical value in df1$a.

1 Answers

Use which with arr.ind

unname(which(as.matrix(df_lgl), arr.ind = TRUE)[, 'col'])
[1] 3
Related