我想创建一个为期14年的6个月间隔向量。目的是我必须使用PerformanceAnalytics
保存一些图表:更具体地说:每六个月charts.PerformanceSummary()
。我不想手动输入每6个月的范围,而是想创建一个带有日期的向量,这样我就可以使用循环来促进这个过程。
我希望该向量包含01-01-2000到12-31-2014之间的日期,格式如下:
DATES
"200001/200006"
"200007/200012"
"200101/200106"
"200107/200112"
"200201/200206"
"200207/200212"
...
"201407/201412"
但是我不知道怎么做这个!
例如:
library(PerformanceAnalytics)
# Load DATA "edhec"
data(edhec)
# Now I can view the chart from "01-01-1999" to "06-30-1999"
charts.PerformanceSummary(edhec[,1]["199901/199906"])
但如果我有DATES矢量,我可以执行以下操作:
# Save formatted dates to "DATES"
DATES <- c("200001/200006","200007/200012")
# Plot Selected Dates only
charts.PerformanceSummary(edhec[DATES[1]])
# OR:
charts.PerformanceSummary(edhec[DATES[2]])
任何帮助表示赞赏!!!
答案 0 :(得分:4)
你可以尝试
indx <- seq(as.Date('2000-01-01'), length.out=30, by='6 month')
indx2 <- seq(as.Date('2000-06-01'), length.out=30, by='6 month')
DATES <- paste(format(indx, '%Y%m'), format(indx2, '%Y%m'), sep="/")
DATES
# [1] "200001/200006" "200007/200012" "200101/200106" "200107/200112"
# [5] "200201/200206" "200207/200212" "200301/200306" "200307/200312"
# [9] "200401/200406" "200407/200412" "200501/200506" "200507/200512"
# [13] "200601/200606" "200607/200612" "200701/200706" "200707/200712"
# [17] "200801/200806" "200807/200812" "200901/200906" "200907/200912"
# [21] "201001/201006" "201007/201012" "201101/201106" "201107/201112"
# [25] "201201/201206" "201207/201212" "201301/201306" "201307/201312"
# [29] "201401/201406" "201407/201412"
或者您可以在loop
DATES1 <- Reduce(function(...) paste(..., sep="/"),
lapply(as.Date(c('2000-01-01', '2000-06-01')),
function(x) format(seq(x,length.out=30, by='6 month'), '%Y%m')))
identical(DATES, DATES1)
#[1] TRUE
答案 1 :(得分:1)
这与lubridate
library(lubridate)
idx1 <- ymd("2000-01-01") + months(seq(from=0, length.out=30, by=6))
idx2 <- idx1 + months(5)
paste0(format(idx1, "%Y%m"), "/", format(idx2, "%Y%m"))
## [1] "200001/200006" "200007/200012" "200101/200106" "200107/200112"
## [5] "200201/200206" "200207/200212" "200301/200306" "200307/200312"
## [9] "200401/200406" "200407/200412" "200501/200506" "200507/200512"
## [13] "200601/200606" "200607/200612" "200701/200706" "200707/200712"
## [17] "200801/200806" "200807/200812" "200901/200906" "200907/200912"
## [21] "201001/201006" "201007/201012" "201101/201106" "201107/201112"
## [25] "201201/201206" "201207/201212" "201301/201306" "201307/201312"
## [29] "201401/201406" "201407/201412"