简体   繁体   中英

Manipulating data with time series on row and column

I am new to R, and am trying to figure out how to manipulate data that has dates along rows and columns.

Basically, I have a data object for a date, let's say 2014-10-31. This object contains futures settlement prices for a couple months going forward:

Date        2014-10-31
2014-11-01       90.54
2014-12-01       90.32
2015-01-01       90.68
2015-02-01       91.48
2015-03-01       91.03

This would exist for every weekday in a year. Now, I want something similar to this:

Date        2014-10-28   2014-10-29   2014-10-30   2014-10-31  ... 
2014-11-01       90.54        90.53        90.57        90.54  ...
2014-12-01       90.21        90.23        90.75        90.32  ...
2015-01-01       90.70        90.45        90.65        90.68  ...
2015-02-01       91.48        91.56        91.53        91.48  ...
2015-03-01       91.02        91.03        91.01        91.03  ...

Currently, in RI have it as a list, with each day as a zoo object, with the settlement date as the name. I know there must be better ways to handle this. Are data frames the better way to go, or are there any packages that can make this easier?

My end goal is to be able to, for example, find the average November prices in October. So I need to get all columns that are in October, and average all the prices of November. Any help would be appreciated.

If you have a list of zoo objects like this:

L <- structure(list(X2014.10.28 = structure(c(90.54, 90.21, 90.7, 
91.48, 91.02), index = structure(c(16375, 16405, 16436, 16467, 
16495), class = "Date"), class = "zoo"), X2014.10.29 = structure(c(90.53, 
90.23, 90.45, 91.56, 91.03), index = structure(c(16375, 16405, 
16436, 16467, 16495), class = "Date"), class = "zoo"), 
X2014.10.30 = structure(c(90.57, 
90.75, 90.65, 91.53, 91.01), index = structure(c(16375, 16405, 
16436, 16467, 16495), class = "Date"), class = "zoo"), 
X2014.10.31 = structure(c(90.54, 
90.32, 90.68, 91.48, 91.03), index = structure(c(16375, 16405, 
16436, 16467, 16495), class = "Date"), class = "zoo")), .Names = c("X2014.10.28", 
"X2014.10.29", "X2014.10.30", "X2014.10.31"))

Then use cbind to merge them together into a single zoo object:

z <- do.call(cbind, L)

giving:

> class(z)
[1] "zoo"
> z
           X2014.10.28 X2014.10.29 X2014.10.30 X2014.10.31
2014-11-01       90.54       90.53       90.57       90.54
2014-12-01       90.21       90.23       90.75       90.32
2015-01-01       90.70       90.45       90.65       90.68
2015-02-01       91.48       91.56       91.53       91.48
2015-03-01       91.02       91.03       91.01       91.03

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