有没有办法 return 管道数据帧的名称

Is there a way to return the name of a piped dataframe

我有一个将数据框作为输入的函数。我想创建一个包含数据框名称的列。就像下面的例子:

the_df <- tibble(a=c(1,2,3),
                 b=c(1,2,3))

func <- function(df){
  df <- df %>% mutate(dataframe = "name_of_df")
  return(df)
}

func(the_df)

这可行吗?

deparse(substitute(..)) 函数将帮助您添加一个新列,其中包含您在函数中传递的任何值。

library(dplyr)

func <- function(df){
  name <- deparse(substitute(df))
  df <- df %>% mutate(dataframe = name)
  return(df)
}

func(the_df)

#      a     b dataframe
#  <dbl> <dbl> <chr>    
#1     1     1 the_df   
#2     2     2 the_df   
#3     3     3 the_df