Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

replace cell values greater than 0 with column name

I have a dataframe with the following structure:

Df = data.frame(
  Col1 = c(1,0,0),
  Col2 = c(0,2,1),
  Col3 = c(0,0,0)
)

What I’m trying to get is a dataframe where those cells with a value greater than 0 get replaced with the column name and those lower than 1 get replaced by NA. The resulting dataframe would be something like this:

Df = data.frame(
      Col1 = c("Col1",NA,NA),
      Col2 = c(NA,"Col2","Col2"),
      Col3 = c(NA,NA,NA)
    )

So far I tried with this solution and with functions like apply(), mutate_if(), and across() but I can’t get what I’m after.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

You could do:

Df %>%
 mutate(across(everything(), ~ if_else(. > 0, cur_column(), NA_character_)))

  Col1 Col2 Col3
1 Col1 <NA> <NA>
2 <NA> Col2 <NA>
3 <NA> Col2 <NA>
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading