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?
Asked
Active
Viewed 48 times
1

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

s_davidsson
- 27
- 6
-
1Does 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 Answers
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"))}

s_davidsson
- 27
- 6
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