Chris
Chris

Reputation: 307

R - add column to dataframe with dataframe name

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"

Upvotes: 3

Views: 109

Answers (1)

r2evans
r2evans

Reputation: 160447

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

Upvotes: 4

Related Questions