-2

I have a data like the following:

df
col1 col2 col3
0     0   1
1     0   0

and I would like to get a result saying in each row which column has the value 1 and return the column name to me. In each row with the columns of consideration, there will only be exactly one "1". There are other values which will be much larger than 1. Without making a new copy of the data with the only three columns, I want to know if there would be efficient ways to extract out the column name.

lll
  • 1,049
  • 2
  • 13
  • 39

1 Answers1

0
apply(df, 1, function(row_tmp){
    which(row_tmp == 1)
})
tobiasegli_te
  • 1,413
  • 1
  • 12
  • 18
  • Thanks for accepting my answer. I realized that you had asked to extract the column names, simply change the part within the function to `names(df)[which(row_tmp == 1)]` to obtain column names. – tobiasegli_te Oct 04 '16 at 19:19