按产品按月汇总R中XTS对象的值
我有一个包含900列(x1-x900)日值的xts对象,我需要将其计算成月度回报按产品按月汇总R中XTS对象的值,r,aggregate,xts,R,Aggregate,Xts,我有一个包含900列(x1-x900)日值的xts对象,我需要将其计算成月度回报 x <- data.frame(date=seq(as.Date("2016/7/4"), as.Date("2016/10/1"), "day"),x1=runif(90,.95,1.07),x2=runif(90,.95,1.07), x3=runif(90,.95,1.07),x4=runif(90,.95,1.07),x5=runif(90,.95,1.07),x6=runif(90,.9
x <- data.frame(date=seq(as.Date("2016/7/4"), as.Date("2016/10/1"), "day"),x1=runif(90,.95,1.07),x2=runif(90,.95,1.07),
x3=runif(90,.95,1.07),x4=runif(90,.95,1.07),x5=runif(90,.95,1.07),x6=runif(90,.95,1.07),x7=runif(90,.95,1.07))
下面是一个带有
dplyr
和lubridate
包的解决方案:
set.seed(1) ; x <- data.frame(date=seq(as.Date("2016/7/4"), as.Date("2016/10/1"), "day"),x1=runif(90,.95,1.07),x2=runif(90,.95,1.07),
x3=runif(90,.95,1.07),x4=runif(90,.95,1.07),x5=runif(90,.95,1.07),x6=runif(90,.95,1.07),x7=runif(90,.95,1.07))
library(dplyr) ; library(lubridate)
x %>%
group_by(yearmon = paste(year(date), month(date), sep = "-")) %>%
summarise_each(funs(prod), - c(date, yearmon))
xts.x和缺少的部分:这里是我的解决方案和FXQuantRader解决方案之间的快速比较。毫无疑问,他的速度要快得多(大约4倍)<代码>库(微基准);微基准(Apom={x%%>%group_by(yearmon=paste(year(date),month(date),sep=“-”))%%>%mutate(date=max(date))%%>%group_by(date)%%>%summary_each(funs(prod),-c(yearmon,date,date)),FXQuantTrader={xts.x
set.seed(1) ; x <- data.frame(date=seq(as.Date("2016/7/4"), as.Date("2016/10/1"), "day"),x1=runif(90,.95,1.07),x2=runif(90,.95,1.07),
x3=runif(90,.95,1.07),x4=runif(90,.95,1.07),x5=runif(90,.95,1.07),x6=runif(90,.95,1.07),x7=runif(90,.95,1.07))
library(dplyr) ; library(lubridate)
x %>%
group_by(yearmon = paste(year(date), month(date), sep = "-")) %>%
summarise_each(funs(prod), - c(date, yearmon))
x %>%
group_by(yearmon = paste(year(date), month(date), sep = "-")) %>%
mutate(Date = max(date)) %>%
group_by(Date) %>%
summarise_each(funs(prod), - c(yearmon, date, Date))
xts.x <- xts(x[, !colnames(x) %in% "date"], order.by = x[, "date"])
xts.x.mthly <- apply.monthly(xts.x, FUN = function(x) unlist(lapply(x, prod)))
> xts.x.mthly
x1 x2 x3 x4 x5 x6 x7
2016-07-31 0.9924681 1.306556 1.0919181 0.8019117 1.3563864 1.853631 0.8563263
2016-08-31 1.4780971 1.946373 1.4265027 1.8508386 1.4926483 1.651613 1.4224733
2016-09-30 1.5926547 1.478231 1.0414107 1.4204825 1.2540149 1.374734 1.0768668
2016-10-01 1.0643725 1.005987 0.9813467 1.0545426 0.9964061 1.005145 1.0146190
# If you want data.frame output with explicit date column:
df.mthly <- data.frame("date" = index(xts.x.mthly), coredata(xts.x.mthly))