0mm3 0mm3 - 1 month ago 6
R Question

R - if row contains x print column header in new column

I am new to R and programming in general. I have a very large data frame containing binary data. I want to read across the rows and where there is a 1 print the column name in a new column at the end. When there are multiple 1's across a row, I would like all of the column headers to be concatenated into a long comma separated list. To explain this better, see the test data frame below:

B <- data.frame(A = c(0, 1, 1, 0),
B = c(0, 1, 0, 1))

A B
1 0 0
2 1 1
3 1 0
4 0 1


The output I want to generate would be:

A B C
1 0 0
2 1 1 A, B
3 1 0 A
4 0 1 B


Where a new column 'C' is created and the column headers for the rows which contain 1 are added to a string.

Thanks

989 989
Answer

Try this:

df$C <- apply(df, 1, function(x) paste0(names(df)[as.logical(x)], collapse = ","))

#  A B   C
#1 0 0    
#2 1 1 A,B
#3 1 0   A
#4 0 1   B