Bobby Bobby - 22 days ago 4x
R Question

Use variable name to define column name 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
, how can I calculate it dynamically?

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

R: Add new column to dataframe using function


We may use substitute inside a function

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

          dat %>%
               mutate(fk_table = name)

#  _ID0 fk_table
#1   z1      dfB
#2   z2      dfB
#3   z3      dfB