使用 R 从 XTS 对象中提取每月第一个工作日的返回值 [英] Pull Return from first business day of the month from XTS object using R
问题描述
我对 R 很陌生,所以如果我在解释这个问题时弄错了任何术语,我深表歉意.
I am very new to R so apologies if I get any of the terminology wrong when I explain this problem.
我在 csv 文件中有一组每日返回数据,我已设法将其转换为 xts 对象.数据格式如下:
I have a set of daily returns data in a csv file that I have managed to convert to an xts object. The data is in the format:
HighYield..EUR. MSCI.World..EUR.
2002-01-31 0.0144 0.0031
2002-02-01 0.0056 -0.0132
2002-02-02 0.0373 0.0356
2002-02-03 -0.0167 -0.0644
2002-02-04 -0.0062 -0.0332
2002-02-05 -0.0874 -0.1112
...
我想创建一个脚本来查找当月的第一个工作日(从索引中的值范围),然后创建一个包含这些返回值的新 xts 对象.
I want to create a script that will find the first business day of the month (from the range of values in the index) and then create a new xts object with these returns in it.
例如,在脚本运行后,我会有一个 xts 对象,格式如下:
For example, after the script has run I would have an xts object in the format:
HighYield..EUR. MSCI.World..EUR.
2002-01-31 0.0144 0.0031
2002-02-28 0.0011 -0.0112
2002-03-31 0.0222 0.0224
2002-04-30 -0.0333 -0.0223
2002-05-30 -0.0011 -0.0012
2002-06-30 -0.0888 -0.0967
...
有人可以帮我吗?如果可能,请解释脚本的每个部分在做什么.
Can someone help me please? and if possible explain what each part of the script is doing.
推荐答案
感谢基础 R 语言的强大功能,您可以在一行中完成:
Thanks to the power of the base R language, you can do this in one line:
library(xts)
data(sample_matrix)
x <- as.xts(sample_matrix)
do.call(rbind, lapply(split(x, "months"), first))
解释每一步的作用:
# Split the xts object into a list with an element for each month.
x1 <- split(x, "months")
# Loop over the list (x1) and call the first() function on each element.
# This returns a new list where each element only contains the first observation
# from each respective element in x1.
x2 <- lapply(x1, first)
# Call rbind() with all the elements of x2 as arguments to rbind()
# Same as rbind(x2[[1]], x2[[2]], ..., x2[[N]])
x3 <- do.call(rbind, x2)
这篇关于使用 R 从 XTS 对象中提取每月第一个工作日的返回值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!