Larusson
Larusson

Reputation: 267

Run external R script n times, with different input paramters, and save outputs in a data frame

my question ties to the following problem:

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

The difference is, that I dont generate different results by randomization functions but would like to use every time a different set of input variables (e.g. run the chunk of code for a range of latitudes lat=c(50,60,70,80))

Has anyone a hint for me? Thanks a lot!

Upvotes: 0

Views: 729

Answers (1)

Nick Kennedy
Nick Kennedy

Reputation: 12640

Wrap the script into a function by putting:

my_function <- function(latitude) {

at the top and

}

at the bottom.

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

results <- ldply(10 * 5:8, myFunction)

If you wanted a column to identify which latitude was used, you could either add that to your function's data.frame or use:

results <- ldply(10 * 5:8, function(lat) data.frame(latitude = lat, myFunction())

If for some reason you didn't want to modify your script, you could create a wrapper function:

my_wrapper <- function(a) {
  latitude <- a
  source("script.R", local = TRUE)$value
}

or even use eval and parse:

my_function <- eval(parse(text = c("function(latitude) {",
  readLines("script.R"), "}")))

Upvotes: 1

Related Questions