1

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.

HongboZhu
  • 4,442
  • 3
  • 27
  • 33
  • In your code, `i` is file name, not file name index. You could try: `read_csv(i)`. Alternatively, use `for (i in seq(length(data))) { read_csv(data[i]) }`. – HongboZhu Oct 30 '20 at 22:31

1 Answers1

0

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))
 }
akrun
  • 874,273
  • 37
  • 540
  • 662