使用R从XTS对象拉出本月第一个工作日的退货

Gre*_*uff 9 r xts

如果我在解释这个问题时得到任何错误的术语,那么我对R很新,所以道歉.

我在csv文件中有一组每日返回数据,我已设法将其转换为xts对象.数据格式如下:

           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 
...
Run Code Online (Sandbox Code Playgroud)

我想创建一个脚本,它将找到该月的第一个工作日(从索引中的值范围),然后创建一个新的xts对象,其中包含这些返回值.

例如,在脚本运行后,我将使用以下格式的xts对象:

           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 
...
Run Code Online (Sandbox Code Playgroud)

有谁可以帮助我吗?并且如果可能的话,解释脚本的每个部分正在做什么.

Jos*_*ich 11

由于基本R语言的强大功能,您可以在一行中执行此操作:

 library(xts)
 data(sample_matrix)
 x <- as.xts(sample_matrix)
 do.call(rbind, lapply(split(x, "months"), first))
Run Code Online (Sandbox Code Playgroud)

要解释每个步骤的作用:

 # 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)
Run Code Online (Sandbox Code Playgroud)