[英]Pull nth Day of Month in XTS in R
使用與您鏈接的問題相同的示例數據,您可以執行一些基本的子集。
這是示例數據:
library(xts)
data(sample_matrix)
x <- as.xts(sample_matrix)
這是子集:
x[format(index(x), "%d") == "10"]
# Open High Low Close
# 2007-01-10 49.91228 50.13053 49.91228 49.97246
# 2007-02-10 50.68923 50.72696 50.60707 50.69562
# 2007-03-10 49.79370 49.88984 49.70385 49.88698
# 2007-04-10 49.55704 49.78776 49.55704 49.76984
# 2007-05-10 48.83479 48.84549 48.38001 48.38001
# 2007-06-10 47.74899 47.74899 47.28685 47.28685
這是你在找什么?
使用%in%
可以提供更多靈活性。 例如,如果你想要每個月的第十天,第十一天和第十二天,你可以x[format(index(x), "%d") %in% c("10", "11", "12")]
使用x[format(index(x), "%d") %in% c("10", "11", "12")]
而不是。
如果您在更新中有想要提取第十個數據點 ,只需使用匿名函數,如下所示:
do.call(rbind, lapply(split(x, "months"), function(x) x[10]))
# Open High Low Close
# 2007-01-11 49.88529 50.23910 49.88529 50.23910
# 2007-02-10 50.68923 50.72696 50.60707 50.69562
# 2007-03-10 49.79370 49.88984 49.70385 49.88698
# 2007-04-10 49.55704 49.78776 49.55704 49.76984
# 2007-05-10 48.83479 48.84549 48.38001 48.38001
# 2007-06-10 47.74899 47.74899 47.28685 47.28685
請注意,第一行是該月的第11天,因為數據實際上是從2007年1月2日開始的。
x[1, ]
# Open High Low Close
# 2007-01-02 50.03978 50.11778 49.95041 50.11778
xts為這些類型的子集提供了一些內置函數。
> data(sample_matrix)
> x <- as.xts(sample_matrix)
> x[.indexmday(x) == 10]
Open High Low Close
2007-01-10 49.91228 50.13053 49.91228 49.97246
2007-02-10 50.68923 50.72696 50.60707 50.69562
2007-03-10 49.79370 49.88984 49.70385 49.88698
2007-04-10 49.55704 49.78776 49.55704 49.76984
2007-05-10 48.83479 48.84549 48.38001 48.38001
2007-06-10 47.74899 47.74899 47.28685 47.28685
請參閱幫助頁面?indexClass
以獲取所有這些頁面的列表。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.