How to mutate across multiple columns and paste the relevant column name as the cell entry?

701 views Asked by At

I'm trying to mutate across multiple columns to paste in the column name as the entry where the entries are/are not NA.

Using airquality dataset

> head(airquality)
  Ozone Solar.R Wind Temp Month Day
1    41     190  7.4   67     5   1
2    36     118  8.0   72     5   2
3    12     149 12.6   74     5   3
4    18     313 11.5   62     5   4
5    NA      NA 14.3   56     5   5
6    28      NA 14.9   66     5   6

I would like to change to this:

> head(airquality)
  Ozone Solar.R Wind Temp Month Day
1    41     190  7.4   67     5   1
2    36     118  8.0   72     5   2
3    12     149 12.6   74     5   3
4    18     313 11.5   62     5   4
5 Ozone Solar.R 14.3   56     5   5
6    28 Solar.R 14.9   66     5   6

I've tried

airquality %>%
  mutate(across(1:2, paste0(cur_column())))

and I get

Error in `mutate()`:
ℹ In argument: `across(1:2, paste0(cur_column()))`.
Caused by error in `cur_column()`:
! Must only be used inside `across()`

I've tried a few other methods of using a function with {{column_name}}, but had no luck.

col_tidy_fun <- function(column_name) {
  mutate({column_name} := case_when(
    !is.na({{column_name}}) ~ paste0("{column_name}"),
    TRUE ~ NA
  ))
}

Any help appreciated.

1

There are 1 answers

2
Sam Talcott On BEST ANSWER

You can use dplyr::if_else (or base ifelse) to determine which values to replace. Either way you'll need to coerce the columns to characters, as you can't have numeric and character values in the same column:

airquality |> 
  mutate(across(everything(), ~if_else(is.na(.), cur_column(), as.character(.))))