运行外部R脚本n次并将输出保存在数据框中 [英] Run external R script n times and save outputs in a data frame

查看:73
本文介绍了运行外部R脚本n次并将输出保存在数据框中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个数百行的R脚本,其中包括几个随机函数.每次运行它,我都会得到不同的结果.

I have a R script of several hundreds of lines including several randomization functions. Each time I run it I obtain a different result.

我正在考虑对模型进行敏感性分析,并且希望对脚本运行数百次并比较结果感兴趣.

I am thinking of performing a sensitivity analysis of my model and I wold be interested in running my script hundreds of times and compare the results.

经过研究,我发现lapplyknitr的组合可能是一种可能的解决方案:

After some research, I found out that a combination of lapply andknitr could be a possible solution:

result <- c("B:/Documents/result.R")
resultsList <- lapply(1:100, function(n) knit(input=result, NULL))

不幸的是,这不起作用.谁能解释我为什么?

Unfortunately this is not working. Could anyone explain me why?

非常感谢!

脚本如下:

#Records
dataID = c(01, 03, 05) 
localityNumber = c(2000, 4000, 5000) 
records = data.frame(dataID, localityNumber)

#Locality number / Postcode conversion table
localityNumber = c(2000, 2000, 2000, 4000, 5000)
postCode = c(6766, 6767, 6768, 7041, 8046) 
allocationTable = data.frame(localityNumber,postCode)

rm(dataID, localityNumber, postCode)

#Create random postcode id
count <- aggregate(allocationTable, by=list(allocationTable$localityNumber), FUN=length)
names(count) <- c("localityNumber", "count", "count.2")
allocationTable <- join(x=allocationTable, y=count)

#Test with for localityNumber with three postcodes
allocationThree <- allocationTable[which (allocationTable$count == "3"),]
testThree <- nrow(allocationThree) / 3
repThree <- rep(1:3, testThree)
allocationThree$id <- repThree
allocationThree$count <- allocationThree$count.2 <- NULL
rm(count, rep, testThree)

records$id <- repThree

#Randomly allocate
records <- join(records, allocationThree)

我想重复执行此脚本几次,并将records data.frame的值存储在列表中.

I would like to repeat this script several times and store the values of the records data.frame in a list.

推荐答案

尝试添加records添加脚本的末尾,以便其输出records数据帧.

Try adding records add the end of your script so that it outputs the records dataframe.

然后您可以运行:

result_list<-lapply(1:100, function(n)source("your_script.R"))

如果要rbind所有数据框,则可以执行以下操作:

If you want to rbind all the dataframes, you can do:

do.call(cbind,lapply(result_list,function(x) x$value))

这篇关于运行外部R脚本n次并将输出保存在数据框中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆