Search code examples
rcsvfor-looploadingreadr

Importing multiple csv files with read_csv in r


I have a vector with the names of multiple csv files.

library(readr)
data<-c("categories.csv",
    "customers.csv",
    "employees.csv",
    "employee_territories.csv",
    "order_details.csv",
    "orders.csv",
    "products.csv",
    "regions.csv",
    "shippers.csv",
    "suppliers.csv", 
    "territories.csv")

and I would like to load all of them with a for loop in my workspace.

My first try was

i<-1
for (i in data) {
  read_csv(data("i"))
}

maybe someone can help me.


Solution

  • We can use map

    library(purrr)
    library(readr)
    out_list <- map(data, read_csv)
    names(out_list) <- sub("\\.csv", "", data)
    list2env(out_list, .GlobalEnv) # not recommended
    

    Or using a for loop, create a NULL list to store the output of the read data, then loop over the 'data', read them and assign it to the output list element

    out_list <- vector('list', length(data))
    names(out_list) <- data
    for(file in data) out_list[[file]] <- read_csv(file)
    

    If we want to create multiple new objects (not recommended)

    for(file in data) {
        assign(sub("\\.csv", "", file), read_csv(file))
     }