Extracting column names with condition from a data frame

You can do:

apply(df[-1], 1, function(x) toString(names(df[-1])[as.logical(x)]))

 [1] "A1, A2" "A1, A2" "A1"     "A1"     ""       "A2, A8" "A6, A8" "A1, A8" "A6, A8" "A8"     "A1, A8" "A6"    
[13] "A5, A8" ""       "A8"     "A8"     "A8"     "A8"     "A8"     "A8"     "A7"     ""

Something like this?

apply(new[,-1],1,function(x){
  paste0(colnames(new)[which(x==1)+1],collapse=",")
})

 [1] "A1,A2" "A1,A2" "A1"    "A1"    ""      "A2,A8" "A6,A8" "A1,A8" "A6,A8" "A8"    "A1,A8" "A6"   
[13] "A5,A8" ""      "A8"    "A8"    "A8"    "A8"    "A8"    "A8"    "A7"    ""

We can get the data in long format, filter rows where value is not 0, group_by ID and create a comma-separated value of each column name.

library(dplyr)

new %>%
  tidyr::pivot_longer(cols = -ID) %>%
  filter(value != 0) %>%
  group_by(ID) %>%
  summarise(name = toString(name))

# A tibble: 19 x 2
#      ID name  
#   <dbl> <chr> 
# 1     1 A1, A2
# 2     2 A1, A2
# 3     3 A1    
# 4     4 A1    
# 5     6 A2, A8
# 6     7 A6, A8
# 7     8 A1, A8
# 8     9 A6, A8
# 9    10 A8    
#10    11 A1, A8
#.....

Tags:

R

Dataframe