0

This question is asked here In R, how to get an object's name after it is sent to a function?

However, this doesn't work when in a for loop. For example the following method will write multiple dataframes to a postgresql database,

write_multiple_to_postgres <- function(list_of_frames) {
for(i in 1:length(list_of_frames)) {
    object_name <- deparse(substitute(list_of_frames[[i]]))
    write_to_postgresql(object_name, list_of_frames[[i]])
    }
}

Where the list_of_frames looks like this:

my_list <- list(data_frame_susan, data_frame_bobby, data_frame_melissa)

....and is called as:

write_multiple_to_postgres(my_list)

I want the object_name to be passed as a string to the write_to_postgresql method. But instead I get the following outputs for object_name

my_list[[1L]], my_list[[2L]], my_list[[3L]]

Where what I want is:

data_frame_susan, data_frame_bobby, data_frame_melissa

How can I use "deparse(substitute) trick" or some other method to get the object name after being passed into a function and used in a for loop?

Community
  • 1
  • 1
Cybernetic
  • 12,628
  • 16
  • 93
  • 132

1 Answers1

0

As you define your list my_list there is no way to get back df name back. You should use a named list such as my_list=list(data_frame_susan=data_frame_susan...) and then have a loop on names(my_list)

for (df in names(my_list)){
write_to_postgresql(df, my_list[[df]])
}

Now the question is how to prepare my_list with corresponding names but with what you say we don't know from where it comes from and how those data.frames are populated.

Eric Lecoutre
  • 1,461
  • 16
  • 25