Search This Blog

10.5.20

How to import multiple .csv files R where files share same column format

Loading multiple csv files in R which share same column format

Scenario - We have number of csv files with identical column format and we would like to import all of this data into one data frames.

Solution - following code can help upload multiple identical files into list of data frames in R and then into one big data frame:



loadDF <- function(directory){

  #set current working directory

  old.WD <- getwd()
  new_WD <- paste(old.WD, "/", directory, sep = "")
  
  #put all filenames that start with numbers in a vector
  # to loop through later
  m.List <- list.files(path = new_WD, pattern = "[0-9]")

  #loop through the files and save data into individual data frames
   i <- 1
   m.list <- list()
  #check all the files matching your criterion. 
  #If you have other csv files in the director differing format then 
  #you may want to put then into different directory or enhance criterion
   while (i < length(m.List)) {
     m.list[[i]] <- read.csv(paste(new_WD,"/",m.List[i], sep = ""), header = TRUE, sep = ",")
     i <- i + 1
   }
  #join all individual data frames into one big data frame  
   m.final <- do.call("rbind", m.list)
   m.final
}
All your identicall csv files are now loaded into one big data frame to process. 

No comments:

Post a Comment