I have created a time series using zoo. It has daily values for a long period of time (40 years). I can easily plot it, but what I want is to create a time series with monthly (mean) values from this original time series and then plot it as monthly values.
I thought the package lubridate could be a good option for this and maybe there is an easy way but I don't see how. I'm a beginner in R. Has somebody a tip here?
You can use apply.monthly()
from the xts package.
library(xts)
data(sample_matrix)
x <- as.xts(sample_matrix, dateFormat = "Date")
(m <- apply.monthly(x, mean))
# Open High Low Close
# 2007-01-31 50.21140 50.31528 50.12072 50.22791
# 2007-02-28 50.78427 50.88091 50.69639 50.79533
# 2007-03-31 49.53185 49.61232 49.40435 49.48246
# 2007-04-30 49.62687 49.71287 49.53189 49.62978
# 2007-05-31 48.31942 48.41694 48.18960 48.26699
# 2007-06-30 47.47717 47.57592 47.38255 47.46899
You might also want to convert your index from Date
to yearmon
, which you can do like this:
index(m) <- as.yearmon(index(m))
m
# Open High Low Close
# Jan 2007 50.21140 50.31528 50.12072 50.22791
# Feb 2007 50.78427 50.88091 50.69639 50.79533
# Mar 2007 49.53185 49.61232 49.40435 49.48246
# Apr 2007 49.62687 49.71287 49.53189 49.62978
# May 2007 48.31942 48.41694 48.18960 48.26699
# Jun 2007 47.47717 47.57592 47.38255 47.46899
You can use aggregate.zoo
as shown in the examples:
x2a <- aggregate(x, as.Date(as.yearmon(time(x))), mean)
if you want to stick to zoo
.
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.