如何在R中的多个不同数据集上运行相同的代码

时间:2017-02-28 23:55:34

标签: r regression apply linear

我正在尝试对六组不同的数据运行一系列固定效果线性回归。对于每个数据集,我想在数据的子集上多次运行回归。

我为一个数据集开发了一次代码。但我想编写通用代码,以便我可以为六个独立的数据集中的每一个运行此代码。

这是我到目前为止使用的示例数据集:

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次?

非常感谢你的帮助。

1 个答案:

答案 0 :(得分:0)

你的示例代码有点复杂,所以我将用一个更简单的例子来解释它:

如果您可以拆分R脚本,可以使用一个脚本包含您要执行的所有功能,另一个脚本可以通过源(...)使用不同的数据集。 非常简单的示例:将此脚本保存为&#34; my_functions.R&#34;在您的工作目录中(或在您调用 source()时指定文件位置):

com.mongodb.MongoSecurityException: Exception authenticating MongoCredential{mechanism=null, userName='content_rw', source='contenttest', password=<hidden>, mechanismProperties={}}
    at com.mongodb.connection.SaslAuthenticator.wrapInMongoSecurityException(SaslAuthenticator.java:157) ~[mongodb-driver-core-3.4.3.jar!/:na]
    at com.mongodb.connection.SaslAuthenticator.access$200(SaslAuthenticator.java:37) ~[mongodb-driver-core-3.4.3.jar!/:na]
    at com.mongodb.connection.SaslAuthenticator$1.run(SaslAuthenticator.java:66) ~[mongodb-driver-core-3.4.3.jar!/:na]
    at com.mongodb.connection.SaslAuthenticator$1.run(SaslAuthenticator.java:44) ~[mongodb-driver-core-3.4.3.jar!/:na]
    at com.mongodb.connection.SaslAuthenticator.doAsSubject(SaslAuthenticator.java:162) ~[mongodb-driver-core-3.4.3.jar!/:na]
    at com.mongodb.connection.SaslAuthenticator.authenticate(SaslAuthenticator.java:44) ~[mongodb-driver-core-3.4.3.jar!/:na]
    at com.mongodb.connection.DefaultAuthenticator.authenticate(DefaultAuthenticator.java:32) ~[mongodb-driver-core-3.4.3.jar!/:na]
    at com.mongodb.connection.InternalStreamConnectionInitializer.authenticateAll(InternalStreamConnectionInitializer.java:109) ~[mongodb-driver-core-3.4.3.jar!/:na]
    at com.mongodb.connection.InternalStreamConnectionInitializer.initialize(InternalStreamConnectionInitializer.java:46) ~[mongodb-driver-core-3.4.3.jar!/:na]
    at com.mongodb.connection.InternalStreamConnection.open(InternalStreamConnection.java:116) ~[mongodb-driver-core-3.4.3.jar!/:na]
    at com.mongodb.connection.DefaultServerMonitor$ServerMonitorRunnable.run(DefaultServerMonitor.java:113) ~[mongodb-driver-core-3.4.3.jar!/:na]
    at java.lang.Thread.run(Thread.java:748) [na:1.8.0_151]
Caused by: com.mongodb.MongoCommandException: Command failed with error 18: 'Authentication failed.' on server a.mongo.db:27017. The full response is { "ok" : 0.0, "code" : 18, "errmsg" : "Authentication failed." }
    at com.mongodb.connection.CommandHelper.createCommandFailureException(CommandHelper.java:170) ~[mongodb-driver-core-3.4.3.jar!/:na]
    at com.mongodb.connection.CommandHelper.receiveCommandResult(CommandHelper.java:123) ~[mongodb-driver-core-3.4.3.jar!/:na]
    at com.mongodb.connection.CommandHelper.executeCommand(CommandHelper.java:32) ~[mongodb-driver-core-3.4.3.jar!/:na]
    at com.mongodb.connection.SaslAuthenticator.sendSaslStart(SaslAuthenticator.java:117) ~[mongodb-driver-core-3.4.3.jar!/:na]
    at com.mongodb.connection.SaslAuthenticator.access$000(SaslAuthenticator.java:37) ~[mongodb-driver-core-3.4.3.jar!/:na]
    at com.mongodb.connection.SaslAuthenticator$1.run(SaslAuthenticator.java:50) ~[mongodb-driver-core-3.4.3.jar!/:na]
    ... 9 common frames omitted

假设您有所有数据集的列表(但也适用于数据框列或任何结构),请通过&#34; source()&#34;来调用第一个脚本:

plot(my.data)

相反,如果您希望将所有内容保存在一个R脚本中,则可以编写一个huuuge函数并将每个数据集作为输入调用此函数:

list.of.my.data <- list(a=1:10, b=11:20, c=21:30)
for (i in 1:length(list.of.my.data)){
  my.data <- list.of.my.data[[i]]
  source("my_functions.R")
  }