简体   繁体   中英

Import multiple csv files in R while retaining their names

How do I import multiple csv files, all in one folder, while retaining their names. For example, if the file a.csv should be imported as "a", b.csv should be imported as "b", etc.

Edit: Just to to be specific... I do NOT want to type out the names of the files individually, because there's a whole bunch of them. I want to have a system which simple reads in all the files from a directory and retains the original file names.

Yadda yadda use a list yadda

filenames <- c("a", "b", "c")

dfs <- setNames(lapply(filenames, function(f)
    read.csv(paste0(f, "csv")), filenames))

use assign . A simple iteration is as follows:

basenames <- c("a", "b" , "c")

lapply(basenames, function(x) 
  assign(x, read.csv(paste0(x, ".csv")), envir=.GlobalEnv)
  )

This is how I do it, like Hong Ooi, with a list...

# assuming your working directory is the folder with the CSVs
myfiles <- dir(pattern = "\\.(csv|CSV)$", full.names = TRUE) # get filenames and paths
myfiles_data <- lapply(myfiles, data.table::fread) # read data from files, quickly
head(myfiles_data[[1]]) # validate file reading
names(myfiles_data) <- myfiles # assign names to list items

Another approach using plyr function:

library(plyr)
mydata = ldply(list.files(pattern = “csv”), function(filename) {
dum = read.table(filename)
    #If you want to add the filename as well on the column
    dum$filename = filename
return(dum)
})

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM