2

Is there a way to extract the input column names from the mutate function?

Given any expressions, I ideally want an output telling me which columns were affected by the mutate call.

For example, I'm supplying a few tidy-based expressions to mutate as shown below

library(dplyr)
out <- iris %>%
  mutate(Species, 
         okay = Species, 
         across(c(Species, Sepal.Length), identity, .names = "{.col}_2"), 
         1:150,
         .keep = "none")

names(out)
#> [1] "Species"        "okay"           "Species_2"      "Sepal.Length_2"
#> [5] "1:150"

Created on 2023-04-20 with reprex v2.0.2

I'd like my output to essentially look something like this:

[1] "Species"      "Species"      "Species"      "Sepal.Length" "1:150" 
Ian Campbell
  • 23,484
  • 14
  • 36
  • 57
NicChr
  • 858
  • 1
  • 9

1 Answers1

1

Maybe create an attribute and extract based on the attribute later

library(dplyr)
out <- iris %>%
  mutate(Species, 
         okay = `attr<-`(Species, "oldname", "Species" ),
         across(c(Species, Sepal.Length), ~ {
      .x <- identity(.x);attr(.x, "oldname") <- cur_column()
     .x}, .names = "{.col}_2"), 
         1:150,
         .keep = "none")
unname(mapply(coalesce, lapply(out, \(x) attr(x, "oldname")), names(out)))
[1] "Species"      "Species"      "Species"      "Sepal.Length" "1:150"       
akrun
  • 874,273
  • 37
  • 540
  • 662
  • That's an interesting approach. Can I ask, are there are any general expressions that might destroy the "oldname" attribute? – NicChr Apr 21 '23 at 08:34