-2

Suppose I have a number of csv files that have the following format:

Date,col1,col2,col3
8/1/2017,2,3,4
8/5/2017,4,6,7

Date,col1,col2,col3
8/1/2017,2,3,4
8/3/2017,2,5,4
8/5/2017,4,6,7

How would I create a 1 zoo object that for each date shows me a total for each column?

Using the file contents above I would like to create the following zoo object:

Date      | col1 | col2 | col3
8/1/2017      4     6      8
8/3/2017      2     5      4
8/5/2017      8    12     14

NOTE: I would prefer a base-R solution (using zoo package is OK)

Denis
  • 11,796
  • 16
  • 88
  • 150
  • Is the format %m/%d/%Y or `%d/%m/%Y – akrun Jul 08 '19 at 13:44
  • 2
    How do you plan on creating a `zoo` object via base R? – Sotos Jul 08 '19 at 13:49
  • 2
    Not my downvote Denis but If I took a guess, the downvote is because you show no effort in solving this yourself – Sotos Jul 08 '19 at 13:53
  • 1
    @Sotos, akrun gave me a good base and I figured out the rest... I updated his answer below... I didn't know how to read-in the files so zoo doesn't create a column for each column in each file. The `lapply` trick is what I was missing. – Denis Jul 08 '19 at 14:00
  • No I meant how would you create an actual `zoo` object using only base R (as your request at the end). Sorry If I misunderstood. I thought there was a base R function for `read.zoo` – Sotos Jul 08 '19 at 14:01

1 Answers1

1

We can use read.zoo by reading the files in a list with lapply

library(zoo)

files <- list.files("C:\\test", pattern = ".*.csv", full.names = TRUE)
out.list <- lapply(files, function(x) read.zoo(x, header=TRUE, sep = ",", index.column = "Date"))
summary <- Reduce("+", do.call(merge, args = c(out.list, retclass = "list", fill = 0)))
colnames(summary) <- colnames(out.list[[1]])
Denis
  • 11,796
  • 16
  • 88
  • 150
akrun
  • 874,273
  • 37
  • 540
  • 662