【发布时间】:2017-02-28 23:55:34
【问题描述】:
我正在尝试对六组不同的数据进行一系列固定效应线性回归。对于每个数据集,我想对数据子集多次运行回归。
我已经为一个数据集开发了一次执行此操作的代码。但我想编写通用代码,以便我可以为六组单独的数据中的每组运行它。
这是我目前使用的示例数据集:
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 对this post 的回答。 -
看来你 lmfun 正在做你正在寻找的东西。不是吗?但是你停在了回归水平。现在您需要通过将所需的过程包装在一个函数中来更进一步
标签: r regression apply linear-regression