1

I have a list of named dataframes and run a function on them as below.

I need to get the name of the dataframe whilst running the function.

In the example below I want to add a column with the name of the dataframe in and have entered paste0("df_name") as a placeholder. How can I replace this to get the name of the actual dataframe?

library(tidyverse)

df_list<-list()

df_list$iris1<-iris[1:50,]
df_list$iris2<-iris[51:100,]
df_list$iris3<-iris[101:150,]

df_name<-function(df){
    df%>%
    mutate(df_name=paste0("df_name"))
}

map(df_list,df_name)
Basil
  • 747
  • 7
  • 18
  • Have you seen [this](https://stackoverflow.com/questions/10520772/in-r-how-to-get-an-objects-name-after-it-is-sent-to-a-function) stackoverflow post? It looks like `quote(df_name)` is what you're after to return `"df_name"`. – apax Jun 07 '23 at 16:41
  • 1
    Or iterate over the _names_ of the list elements rather than the elements themselves... – Limey Jun 07 '23 at 16:45

1 Answers1

2

I wouldn't mess with complicated computations on expressions, just use purrr::imap():

df_name <- function(df,nm){
  df |>
    mutate(nm = nm)
}

imap(df_list,.f = ~df_name(.x,.y))

imap() maps over the names & elements of a list in tandem, so you have access to both the list element and it's name in the function you're applying. It's just a convenience function around map2().

joran
  • 169,992
  • 32
  • 429
  • 468