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

痞子三分冷 提交于 2019-12-01 03:29:21

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)
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!