0
我試圖在六組不同的數據集上運行一系列固定效應線性迴歸。對於每個數據集,我想在數據的子集上多次運行迴歸。如何在R中的多個不同數據集上運行相同的代碼
我爲一個數據集開發了一次代碼。但我想編寫通用代碼,以便我可以爲六個獨立的數據集中的每一個運行此代碼。
這是我迄今使用例如數據集:
month <- (rep(0:35, 36))
monthfact <- as.factor(month)
prodid2<- as.character(rep(112:147, 36))
log_value <- rnorm(1296)
exp_share <- abs(rnorm(1296))
regdat <- data.frame(month, monthfact, prodid2, log_value, exp_share)
#Subset the data into 24 datasets, each of which includes a 13 month window
subfun<-function(x,y,z) { subset(x,y>=z & y<=z+12)}
dsets <- lapply(1:24, function(x) subfun(regdat, regdat$month, x-1))
#Writing a function for running linear regressions
lmfun<-function(data){ lm(log_value~monthfact+prodid2, data = data,
weights = data$exp_share)}
#Apply the function to all the datasets in the list
linreg<-lapply(dsets,lmfun)
coefs<-lapply(linreg,coef)
#Choose only the coefficients for month
coefs <- as.data.frame(lapply(coefs, function(x) {x[2:13]}))
#Add in a row of 0 values for the baseline month
baseline<-rep(0,each=24)
coefs<-rbind(baseline,coefs)
#Compute the index using the dataframe created
FEindexes<-data.frame(lapply(coefs, function(x) (exp(x))/(exp(x[1]))))
splices<-FEindexes[2,]
splices <- apply(splices, 1, cumprod)
splices <- c(1,splices[1:23])
FEindex13<-t(FEindexes[13,])
FEWS<-splices*FEindex13
FEWS<-as.data.frame(FEWS[2:24])
firstFEWS<-as.data.frame(FEindexes[,1])
colnames(firstFEWS) <- "FEWS_index"
colnames(FEWS) <- "FEWS_index"
FEWS<-rbind(firstFEWS,FEWS)
View(FEWS)
我想在6點不同的數據集運行所有這些代碼,並想知道如果有一種方法R中做到這一點,而無需重新運行所有代碼6次?
非常感謝您的幫助。
我建議把data.frames放到一個列表中,然後用'lapply'來遍歷它們。有關提示,請參閱gregor對[本文](http://stackoverflow.com/questions/17499013/how-do-i-make-a-list-of-data-frames)的回答。 – lmo
似乎你lmfun正在做你正在尋找的東西。不是嗎?但你停在迴歸水平。現在,您需要通過在功能內包裝所需的過程來進一步完善 – DJJ