1

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)
jeetkamal
  • 399
  • 2
  • 12
sim235
  • 219
  • 1
  • 9
  • But your items in a list. Try `list_all<-list(list_csfiles, list_tsfiles, list_dmfiles, list_tmfiles)`. If that doesn't work then describe what you mean by "is not working". Are you getting an error? Something other than what you were expecting? It's easier to help you if you include a simple [reproducible example](https://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example) with sample input and desired output that can be used to test and verify possible solutions. We currently can't test because we don't have any data. – MrFlick Jul 25 '20 at 05:59

2 Answers2

5

Create a named list :

list_all<- dplyr::lst(list_csfiles,list_tsfiles,list_dmfiles,list_tmfiles)

In the function pass data and name seperately :

newey<-function(list_files, name) {
  #All the code as it is
  #...
  #...
  #...
  write.xlsx(cs_nw_full, paste0(name, ".xlsx"))
}

You can then use Map :

Map(newey, list_all, names(list_all))

Or with purrr::imap

purrr::imap(list_all, newey)
Ronak Shah
  • 377,200
  • 20
  • 156
  • 213
1

Make a master list of all list objects. And then apply mapply() on it.

list_all<-list(list_csfiles,list_tsfiles,list_dmfiles,list_tmfiles)
mapply(newey,list_all)

jeetkamal
  • 399
  • 2
  • 12