Search code examples
rcountr-colnames

print column name when specific row of a column contains string in R


I have the following dataset

A    B    C    D
1!   0!   1!   0!
0!   .    1!   1!

I need to print the column name to each match as follows

matches_1     matches_0
A,C           B,D
C,D           A

I'm using:

df$matches_1 <- colSums(apply(df, 1, stringr::str_count, "1!"))

to count occurences of 1! in each row, but i'm not sure how to print the column name instead of the sum


Solution

  • Using == instead of stringr, then extracting the matching colnames, finally paste the result to get the desired output.

    srch <- c("1!", "0!")
    
    data.frame(
      sapply(srch, \(n) 
        apply(df == n, 1, \(x) paste(colnames(df)[x], collapse=","))), check.names=F)
       1!  0!
    1 A,C B,D
    2 C,D   A