Run external R script n times and save outputs in a data frame

喜夏-厌秋 提交于 2019-12-24 02:07:02

问题


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.

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?

Many thanks!

UPDATE

The script looks like this one:

#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)

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


回答1:


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

You can then run:

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

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

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



回答2:


Another option would be to wrap the script into a function by putting:

my_function <- function() {

at the top and

}

at the bottom.

That way, you could source it once then then use ldply from the plyr package:

results <- rdply(100, myFunction())

If you wanted a column to identify which iteration, you could use:

results <- ldply(1:100, function(i) data.frame(iteration = i, myFunction())



回答3:


you can try the following command; Note that you can change the times to whatever number you want

repeatedfunction <- c(mapply(list, FUN=**the name of your function** (args),times=100 ))


来源:https://stackoverflow.com/questions/28792801/run-external-r-script-n-times-and-save-outputs-in-a-data-frame

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!