Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Add file name as a column in each dataframe in a list

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?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading