lll lll - 1 year ago 69
R Question

R: how to which columns contains 1 in the same row

I have a data like the following:

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.

Answer Source
apply(df, 1, function(row_tmp){
    which(row_tmp == 1)
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download