1

First Question/Post, Hopefully I've not duplicated this but have searched as many terms as I can think of. I'm sure this is going to be a "doh" moment, But here goes:

Using R I'm trying to read in several 100 .csv files, of two columns each, type and time elapsed, eg:

Col1    Col2
Type A  11:20:15
Type B  29:40:34
Type C  45:13:26

I'm trying to merge every file in the folder to produce a single DF with a sum of all the times, but I'm drawing a blank really appreciate any guidance to right functions to look at or solutions

Here's Where I'm at:

    files = list.files(pattern="*.csv")
    fileno <- length(files)

    for (i in 1:fileno){
    assign(files[i], read.csv(files[i]))
    ###Code to Read each "time" and Sum with current
    # TotalDF <- Time Value from Current loaded CSV "Summed" to TotalDF
    }

If I had two files:

Col1    Col2
Type A  11:20:15
Type B  29:40:34
Type C  45:13:26

Col1    Col2
Type A  5:00:00
Type B  3:00:00
Type C  8:00:00

Then TotalDF would be:

Col1    Col2
Type A  16:20:15
Type B  32:40:34
Type C  53:13:26
NoobMat
  • 73
  • 1
  • 1
  • 5
  • If you wanted to merge them in the sense what `merge` means in R, you could have a look [here](http://stackoverflow.com/questions/27747716/how-to-merge-multiple-excel-files) for some ideas. – talat Jan 20 '15 at 10:29

1 Answers1

2

You can load all of them into a list and use Reduce.

# define a vector with the file paths
nameFolder <- "data"
vectorFiles <- list.files(nameFolder, full.names = TRUE)

# load each file and change the name of the second column
listDf <- lapply(vectorFiles, function(fileName){
  dfFile <- read.csv(fileName)
  names(dfFile)[2] <- fileName
  return(dfFile)
})

# merge the data frames on the column Col1
dfMerged <- Reduce(function(...) merge(..., by = "Col1"), listDf)
Michele Usuelli
  • 1,970
  • 13
  • 15
  • That's almost perfect, thanks, it gets me almost where I need to be Just need to combine the columns [2] onwards to a total, but I'll try to work out that myself as a learning exercise – NoobMat Jan 20 '15 at 12:22
  • @NoobMat, if this answer works for you, please consider marking it as the answer to your question. – Richard Erickson Jan 20 '15 at 14:43
  • 1
    Hi Richard, thanks, Have done so, But reserve the right to return when I fail dramatically to combine the values :o) Thanks all for help with first SO foray! – NoobMat Jan 20 '15 at 15:05