Reputation: 874
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
Upvotes: 0
Views: 55
Reputation: 19271
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
Upvotes: 1
Reputation: 61214
We can write a customized function:
my_matches <- function(df, match){
tmp <- data.frame(which(df == match, arr.ind = TRUE))
tmp <- split(tmp, tmp$row)
tmp <- sapply(1:length(tmp), \(x) paste0(names(df)[tmp[[x]][,2]], collapse = ","))
return(tmp)
}
library(dplyr)
df %>%
mutate(matches_1 = my_matches(., "1!"),
matches_0 = my_matches(., "0!"))
which produces:
A B C D matches_1 matches_0
1 1! 0! 1! 0! A,C B,D
2 0! . 1! 1! C,D A
Upvotes: 0