MichiZH
MichiZH

Reputation: 5807

R: replace values in a dataframe >0 with the columname

I have a data frame like this

ColumnName1 ColumnName2 ColumnName3...
   0.0         0.2          0.0   
   0.2         0.0          0.0  

In this dataframe there is always one (and only one!) column with a value >0. So instead of the value 0.2 I want the column name in this cell. So in the end I want a new dataframe showing only the columns with a value greater than 0. How can I achieve this?

ColumnName2
ColumnName1
...

This correctly selects the data:

Test[Test>0]

However this always returns NULL:

colnames(Test[Test>0])

Upvotes: 1

Views: 52

Answers (2)

Henrik
Henrik

Reputation: 67778

Something like this maybe

apply(df, 1, function(x){names(x)[x > 0]})
# [1] "ColumnName2" "ColumnName1"

Upvotes: 1

droopy
droopy

Reputation: 2818

to continue with boolean you can try :

colnames(tab)[colSums(t(tab>0)*(1:ncol(tab)))]
# or
apply(tab>0, 1, function(x) colnames(tab)[x])

Upvotes: 1

Related Questions