replace cell values greater than 0 with column name

replace cell values greater than 0 with column name

Problem Description:

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.

Solution – 1

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>
Rate this post
We use cookies in order to give you the best possible experience on our website. By continuing to use this site, you agree to our use of cookies.
Accept
Reject