Pull Return from first business day of the month from XTS object using R

后端 未结 1 1093
清酒与你
清酒与你 2021-01-11 21:22

I am very new to R so apologies if I get any of the terminology wrong when I explain this problem.

I have a set of daily returns data in a csv file that I have manag

相关标签:
1条回答
  • 2021-01-11 22:04

    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))
    

    To explain what each step is doing:

     # 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)
    
    0 讨论(0)
提交回复
热议问题