如何使用不需要手动输入的代码在数据框中创建重复对象名称的列

How to create columns in a data frame with the name of the object repeated using code that doesn't require manual input

我想知道如何使用不需要手动输入的代码在数据框中创建重复对象名称的列。

例如,我可以使用以下代码手动执行此操作:

# displays df
mtcars

# adds column manually
# ---- NOTE: REQUIRES MANUAL INPUT
mtcars$dataset_name <- c("mtcars")

# gives unique values for mtcars$dataset_name
unique(mtcars$dataset_name)

有没有自动执行此操作的方法?

谢谢。

我们可以创建一个将对象作为输入的函数,returns 包含对象名称的列

f1 <- function(dat) {
        nm1 <- deparse(substitute(dat))
        dat$dataset_name <- nm1
        dat
  }
f1(mtcars)