I have a list. List consists of 5 xts objects. Each object consists of 5 xts series. Each series consists of 183 observations. I want to extract one common series from all these series. The series I want to subtract is named risk_free
. I have produced minimal example. In last line code produces error.
library(zoo)
library(xts)
library(PerformanceAnalytics)
managers_1 <- managers[,1:2]
manager_2 <- managers[,3:4]
list_managers <- list(managers_1,manager_2)
risk_free <- managers[,1]
## subtracting risk_free from all columns of all xts objects
list_managers_rf <- lapply(list_managers,"-",risk_free)
You get this error because xts objects always have a dim
attribute (i.e. they're always a matrix). This differs from zoo, where dim
will be dropped if the zoo object can be a vector.
So you can do this if you remove the dim
attribute from risk_free
before subtracting from the xts object with multiple columns. You can do that easily with drop()
.
list_managers_rf <- lapply(list_managers, "-", drop(risk_free))
lapply(list_managers_rf, tail, 2)
## [[1]]
## HAM1 HAM2
## 2006-11-30 0 0.0089
## 2006-12-31 0 -0.0177
##
## [[2]]
## HAM3 HAM4
## 2006-11-30 0.0152 0.0256
## 2006-12-31 -0.0005 0.0091