Home > Net >  Read in CSV files and Add a Column with File name
Read in CSV files and Add a Column with File name

Time:01-31

Assume you have 2 files as follows.

file_1_october.csv
file_2_november.csv

The files have identical columns. So I want to read both files in R which I can easily do with map. I also want to include in each read file a column month with the name of the file. For instance, for file_1_october.csv, I want a column called “month” that contains the words “file_1_october.csv”.

For reproducibility, assume file_1_october.csv is

name,age,gender
james,24,male
Sue,21,female

While file_2_november.csv is

name,age,gender
Grey,24,male
Juliet,21,female

I want to read both files but in each file include a month column that corresponds to the file name so that we have;

name,age,gender,month
james,24,male, file_1_october.csv
Sue,21,female, file_1_october.csv

AND

name,age,gender,month,
Grey,24,male, file_2_november.csv,
Juliet,21,female, file_2_november.csv

CodePudding user response:

Maybe something like this?

csvlist <- c("file_1_october.csv", "file_2_november.csv")

df_list <- lapply(csvlist, function(x) read.csv(x) %>% mutate(month = x))

for (i in seq_along(df_list)) {
  assign(paste0("df", i), df_list[[i]])
}

The two dataframes will be saved in df1 and df2.

  •  Tags:  
  • Related