R:将日数据转换为月平均值
我能够将每日H、L、C数据转换为每月H、L、C数据:R:将日数据转换为月平均值,r,xts,R,Xts,我能够将每日H、L、C数据转换为每月H、L、C数据: library(xts) data(sample_matrix) samplexts <- as.xts(sample_matrix) to.monthly(sample xts) 库(xts) 数据(样本矩阵) samplexts这里有一种使用dplyr包的方法 # create sequence of data dates = seq(as.Date('2011-01-01'),as.Date('2011-12-31'),by
library(xts)
data(sample_matrix)
samplexts <- as.xts(sample_matrix)
to.monthly(sample xts)
库(xts)
数据(样本矩阵)
samplexts这里有一种使用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
使用xts有两种方法
简单方法:使用apply.x
函数(其中x是周期)。在这种情况下适用。每月:
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
或者使用调用apply.monthly
和其他apply.x函数时使用的period.apply
更复杂的方法。如果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
太好了。非常感谢你的帮助。