Search code examples
rreadr

read csv file from list but add the filename as identifier


I have list of csv files. I could read them all using read_csv.

But I would like to add the filename as identifier. How do I do it ?

library(tidyverse)

# read file names
csv_filenames <- list.files(path = "OMITTED FOR THIS EXAMPLE", 
                            full.names = TRUE)


###
csv_filenames are "One.csv", "Two.csv", "Three.csv", ....
###

# read csv files
df <- read_csv(csv_filenames)


Solution

  • read_csv has an argument id = ; if you specify "path", you get a column named "path" with the file names:

    csv_data <- read_csv(csv_filenames, id = "path")
    

    If you wanted just the base file name, you could add a dplyr::mutate step:

    library(dplyr)
    csv_data <- read_csv(csv_filenames, id = "path") %>%
      mutate(path = basename(path))