在 R 中的 XTS 中拉出每月的第 n 天 [英] Pull nth Day of Month in XTS in R

查看:29
本文介绍了在 R 中的 XTS 中拉出每月的第 n 天的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的问题与这里提出的问题密切相关:使用 R 从 XTS 对象中提取每月第一个工作日的返回.

My questions is closely related to the one asked here: Pull Return from first business day of the month from XTS object using R.

我想提取每个月的第 10 个数据点,而不是提取每个月的第一天.我该怎么做?

Instead of extracting the first day of each month, I want to extract, say the 10th data point of each month. How can I do this?

推荐答案

使用来自您链接到的问题的相同示例数据,您可以进行一些基本的子集设置.

Using the same example data from the question you've linked to, you can do some basic subsetting.

这是示例数据:

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")] 代替.

Using %in% would give you some more flexibility. For instance, if you wanted the tenth, eleventh, and twelfth days of each month, you could use x[format(index(x), "%d") %in% c("10", "11", "12")] instead.

如果您在更新中想要提取第十个数据点,只需使用匿名函数,如下所示:

If, as you have in your update, you want to extract the tenth data point, just use an anonymous function as follows:

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

请注意,第一行是当月的第十一天,因为数据实际上是从 2007 年 1 月 2 日开始的.

Note that the first row is the eleventh day of the month, because the data actually starts on January 2, 2007.

x[1, ]
#                Open     High      Low    Close
# 2007-01-02 50.03978 50.11778 49.95041 50.11778

这篇关于在 R 中的 XTS 中拉出每月的第 n 天的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆