Home > Net >  Add file name as a column in each dataframe in a list
Add file name as a column in each dataframe in a list

Time:11-11

I am attempting to add a new column to each dataframe in a list of 131 dataframes, the content of this new column being the name of the file of the original data frame. Here are the steps I have completed so far, after which I have struggled:

#Libraries:
library(dplyr)


#Making a list of all files in my working directory that begin with "i_":

list_of_files <- list.files(pattern = "i_")

#Creating a list of those dataframes, reading them in as csvs:

my_data <- lapply(list_of_files, read.csv)

#I have then tried to mutate across these dataframes, to no avail, with very low quality code:

datamap <- lapply(my_data, ~ .x %>% 
      mutate(file_title = file_id())) 

Does anyone know how to complete this task?

CodePudding user response:

library(tidyverse)
my_data <- imap(my_data, ~ .x %>% mutate(file_title = .y))

The imap() function defines two automatic variables: .x, which is the regular element of my_data, while .y is the corresponding name of the element in my_data.

  • Related