1

I have a chr-vector (filenames) cointaining a series of text strings eg. ("file1.csv", "file2.csv", "file3.csv"). These strings match the file names of csv-files in my working directory, that I wish to read in. Is there a way for me to (programmatically) read in these files and create them as new objects in my global environment?

Anoushiravan R
  • 21,622
  • 3
  • 18
  • 41
  • 1
    Does the following link answer your question? https://stackoverflow.com/questions/11433432/how-to-import-multiple-csv-files-at-once – Anoushiravan R May 10 '21 at 10:31

2 Answers2

0

Thank you Anoushiravan!

I finally came to this solution:

filenames <- gsub("\\.csv$", "", list.files(pattern = "\\.txt$"))

for(i in filenames) {assign(file, read.csv(paste0(i, ".txt"))}
0

I think you can use the following code:

# First you create a character vector of file names with `.csv` extension
tmp <- list.files(pattern = ".csv")

# Then you use `lapply` to apply `read.csv` on every file name to be read.
# The output is a list whose elements are data frames

library(magrittr)

dt <- lapply(tmp, read.csv) %>%
  setNames(gsub(".csv", "", tmp))

# Split the list based on the names of the elements
list <- split(dt, names(dt))

# Save them as objects in the global env
list2env(list, envir = globalenv())

For more thorough information refer to the link I put above your question yesterday.

Anoushiravan R
  • 21,622
  • 3
  • 18
  • 41