jaykay
jaykay

Reputation: 41

R mutating column with dataframe name for a list of dataframes

I am trying to automate the creation of a column (titled FXN) for all dataframes in a given list of dataframes, such that the name of the column is generated:

I tried lapply approach, but am not sure how to retrieve the respective file name from each respective listed dataframe

#read in list of dataframe (ldf)
ldf <- lapply("directory", read.delim)    

#function to generate column FXN with respective df name
lapply(ldf, function(x) {
mutate(x,
       FXN = deparse(substitute(x)))})

However this just results in a column FXN that contains the value x; I would've expected deparse and substitute to pull out respective dataframe names.

Upvotes: 1

Views: 358

Answers (1)

Martin Gal
Martin Gal

Reputation: 16998

You could use purrr's map2-function:

library(dplyr)
library(purrr)

ldf %>% 
  map2(names(.), ~mutate(.x, FXN = .y))

Upvotes: 1

Related Questions