Bobby Bobby - 2 months ago 9
R Question

Use variable name to define column contents with mutate

I have a data frame defined in this way:

dfB <- data.frame("_ID0" = c("z1", "z2", "z3"), check.names = FALSE)


I would like to add a column as shown below:

dfB %>% mutate(fk_table = "dfB")


Instead of hard coding
"dfB"
, how can I calculate it dynamically?


I've found an example here which calculates column names dynamically with
mutate
but doe not use the name of the variable passed.

R: Add new column to dataframe using function

Answer

We may use substitute inside a function

f1  <- function(dat) {
          name <- deparse(substitute(dat))
          #or
          #name <- as.character(match.call()[-1])

          dat %>%
               mutate(fk_table = name)
 }

f1(dfB)
#  _ID0 fk_table
#1   z1      dfB
#2   z2      dfB
#3   z3      dfB