[英]Applying same function to multiple objects in R (for-loop?)
[英]Applying same function on multiple objects in R
我開發了一個 function 將對某些系列進行一些計量經濟學測試。 我想在多個對象上同時運行這個 function。 我正在使用 lapply function 但它正在生成以下錯誤。 [.data.frame
(tsmom, , 1:5) 中的錯誤:選擇了未定義的列。 如果我單獨運行此 function ,則 function 工作正常。 檢查我的代碼
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)
創建一個命名列表:
list_all<- dplyr::lst(list_csfiles,list_tsfiles,list_dmfiles,list_tmfiles)
在 function 中分別傳遞數據和名稱:
newey<-function(list_files, name) {
#All the code as it is
#...
#...
#...
write.xlsx(cs_nw_full, paste0(name, ".xlsx"))
}
然后您可以使用Map
:
Map(newey, list_all, names(list_all))
或者使用purrr::imap
purrr::imap(list_all, newey)
制作所有列表對象的主列表。 然后在其上應用 mapply() 。
list_all<-list(list_csfiles,list_tsfiles,list_dmfiles,list_tmfiles)
mapply(newey,list_all)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.