-1

I have a folder that contains 332 .csv files, from 001.csv to 332.csv. They have the same header. If I want to calculate the mean of an object from the files (its names is from a.csv to b.csv). How can I merge data in file a,a+1,a+2,...b into a dataframe? Example: Input 5:130; Process: reading data from files 005.csv, 006.csv, 007.csv, ..., 130.csv then merging them in a dataframe.

Jaap
  • 81,064
  • 34
  • 182
  • 193
user3690734
  • 1
  • 1
  • 1
  • 1
    I think the question has been answered before http://stackoverflow.com/questions/11433432/importing-multiple-csv-files-into-r – Pork Chop May 30 '14 at 09:49
  • What do you mean by dataframe? Would it be sufficient (and possible) to simply read x csv-files and and use cbind() to join them? If so, you could write a simple loop. – roschu May 30 '14 at 09:49
  • 1
    You could import each file into a third dimension of an `array` and go from there. – Roman Luštrik May 30 '14 at 09:59
  • In my opinion there is no complete answer on the other question which answers this question. I think it is therefore not correct to mark this question as duplicate. – Jaap May 30 '14 at 19:48

1 Answers1

4

Supposing you have all the .csv files in one folder, the following function will give you what you need:

# defining the function
merged <- function(id = 1:332) {
  df <- data.frame()
  for(i in 1:length(id)){
    add <- read.csv(as.character(paste0(sprintf("%03s",id[i]),".csv")))
    df <- rbind(df,add)
  }
  colnames(df) <- c(..specify the colnames in here..)
  assign("dat", df, envir = .GlobalEnv)
}

# getting your merged df
merged(5:130)

The merged dataframes are now in the dataframe dat

Jaap
  • 81,064
  • 34
  • 182
  • 193
  • Something goes wrong. Actually, paste0(sprintf("%03s",id[i]),".csv") just returns " id[i].csv". For example, paste0(sprintf("%03s",1),".csv") returns " 1.csv" – user3690734 May 31 '14 at 01:14
  • That's strange. I tested this on probably the same set of `csv` files (from the Coursera course "Computing for Data Analysis" / "R programming") and it works perfectly. For this function to work, you have to set the working directory to the directory were all the `csv` files are located. After that you can use the function. – Jaap May 31 '14 at 07:56