dplyr::funs() soft deprecated - update to return variable name

Viewed 105

Have spent a lot of time on this so hoping someone can advise. I have a piece of code that used funs(), which is soft deprecated and so have tried the alternative but cannot get it to work as expected.

Old:

df %>% mutate_at(vars(x,y,z), 
                 .funs = funs(Comment = case_when(
  .%in% "YES") ~ deparse(substitute(.))))

This gives the three new variables: x_Comment, y_Comment & z_Comment - and will contain the relevant variable name ("x", "y" or "z") if the relevant variable contains "YES"

Updated:

df %>% mutate_at(vars(x,y,z), 
                 .funs = list(Comment = ~case_when(
  .%in% "YES") ~ deparse(substitute(.))))

I have updated the code based on the warnings about funs() being soft deprecated however the above doesn't work. It gives the three new variables as expected: x_Comment, y_Comment & z_Comment - however if the relevant variable contains "YES" it give "." instead of the variable name.

Any solutions - preferably tidyverse very much so appreciated!

Thanks!

1 Answers

Does this do what you want?

library(tidyverse)

df <- tibble(
        x=c("Yes", "No",  "No"),
        y=c("No",  "Yes", "No"),
        z=c("No",  "No",  "Yes")
)

df %>% 
    mutate(
      across(everything(), 
      ~ifelse(.x == "Yes", cur_column(), ""), 
      .names="Comment_{col}")
    )
# A tibble: 3 x 6
  x     y     z     Comment_x Comment_y Comment_z
  <chr> <chr> <chr> <chr>     <chr>     <chr>    
1 Yes   No    No    "x"       ""        ""       
2 No    Yes   No    ""        "y"       ""       
3 No    No    Yes   ""        ""        "z"   

Note that mutate_at is also deprecated.

Related