I develop a function that will do some econometric test on some series. I want to run this function simultaneously on multiple objects. I am using lapply function but it is generating following error. Error in [.data.frame
(tsmom, , 1:5) : undefined columns selected. If I run this function individually the function is working properly. Check my code
library(xts)
library(zoo)
library(lmtest)
library(sandwich)
list_tsfiles<-list.files(pattern = "^tsmom.*?.*\\.xlsx$")
list_csfiles<-list.files(pattern = "^csmom.*?.*\\.xlsx$")
list_dmfiles<-list.files(pattern = "^dualmom.*?.*\\.xlsx$")
list_tmfiles<-list.files(pattern = "^tpmom.*?.*\\.xlsx$")
newey<-function(list_files){
tsmom<-do.call(cbind,lapply(list_files,function(x) read_excel(x)[,2]))
tsmom<-xts(tsmom[,1:5],order.by = seq(as.Date("2005-02-01"),length=183,by="months")-1)
names(tsmom)<-c("tsmom121","tsmom123","tsmom126","tsmom129","tsmom1212")
## newey west
newey_west<-function(x){
model<-lm(x~1)
newey_west<-coeftest(model,vcov=NeweyWest(model,verbose=T))
newey_west[c(1,3,4)]
}
## running newey west
cs_nw_full<-do.call(cbind,lapply(tsmom,newey_west))
library(gtools)
p_values<-cs_nw_full[3,]
cs_nw_full[2,]<-paste0(cs_nw_full[2,],stars.pval(p_values))
write.xlsx(cs_nw_full, paste0(deparse(substitute(list_files)), ".xlsx"))
}
## Applying the function on all objects simtanously
list_all<-c(list_csfiles,list_tsfiles,list_dmfiles,list_tmfiles)
lapply(list_all,newey)
## Individually running this function
newey(list_csfiles)