How to replace certain values with their column name

  • A+
Category:Languages

I have a following table in R

df <- data.frame('a' = c(1,0,0,1,0),                  'b' = c(1,0,0,1,0),                  'c' = c(1,1,0,1,1)) df    a  b  c 1  1  1  1 2  0  0  1 3  0  0  0 4  1  1  1 4  0  0  1 

What I want is to replace the row value with the column name whenever the row is equal to 1. The output would be this one:

   a  b  c 1  a  b  c 2  0  0  c 3  0  0  0 4  a  b  c 4  0  0  c 

How can I do this in R? Thanks.


I would use Map and replace:

df[] <- Map(function(n, x) replace(x, x == 1, n), names(df), df) df #   a b c # 1 a b c # 2 0 0 c # 3 0 0 0 # 4 a b c # 5 0 0 c 

Comment

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: