sim235
sim235

Reputation: 219

Applying same function on multiple objects in R

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)

Upvotes: 1

Views: 797

Answers (2)

Ronak Shah
Ronak Shah

Reputation: 389315

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)

Upvotes: 5

jeetkamal
jeetkamal

Reputation: 409

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)

Upvotes: 1

Related Questions