我能够将每日的H,L,C数据转换为每月的H,L,C数据:
library(xts)
data(sample_matrix)
samplexts <- as.xts(sample_matrix)
to.monthly(sample xts)
但是如何从每日数据中轻松获取每月平均值?
答案 0 :(得分:2)
使用xts的方法有2种
简单方法:使用apply.x
函数(其中x是句点)。在这种情况下,apply.monthly
:
apply.monthly(samplexts, 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
或更复杂的使用period.apply
的方法,该方法用于调用apply.monthly
和其他apply.x函数。如果apply.x函数缺少时间段,这可以为您提供更精细的控制。
period.apply(samplexts, INDEX = endpoints(samplexts, on = "months"), FUN = 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
答案 1 :(得分:1)
这是使用dplyr软件包的一种方法
# create sequence of data
dates = seq(as.Date('2011-01-01'),as.Date('2011-12-31'),by = 1)
data = data.frame(dates, num = rnorm(1:365))
# create month and year column
data$month = lubridate::month(data$dates)
data$year = lubridate::year(data$dates)
# view data
head(data)
# load library
library(dplyr)
# summarize data as needed
data %>% group_by(year,month) %>% summarize(numMean = mean(num)) %>% as.data.frame