Home > Software design >  R - add column to dataframe with dataframe name
R - add column to dataframe with dataframe name

Time:10-02

is there a way to add a column to dataframe that will contain DF name? Something like in the code below but without typing the name manually?

my_own_df_name <- data.frame(x = c(1,2,3))

my_own_df_name$name <- "my_own_df_name"

CodePudding user response:

You can create a function and use deparse(substitute(.)) to get the object name:

fun <- function(z) { nm <- deparse(substitute(z)); transform(z, name = nm); }
my_own_df_name <- fun(my_own_df_name)
my_own_df_name
#   x           name
# 1 1 my_own_df_name
# 2 2 my_own_df_name
# 3 3 my_own_df_name

quux <- my_own_df_name
fun(quux)
#   x name
# 1 1 quux
# 2 2 quux
# 3 3 quux
  •  Tags:  
  • r
  • Related