Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

R Script as a Function

Tags:

function

r

I have a long script that involves data manipulation and estimation. I have it setup to use a set of parameters, though I would like to be able to run this script multiple times with different sets of inputs kind of like a function.

Running the script produces plots and saves estimates to a csv, I am not particularly concerned with the objects it creates.

I would rather not wrap the script in a function as it is meant to be used interactively. How do people go about doing something like this?

I found this for command line arguments : How to pass command-line arguments when source() an R file but still doesn't solve the interactive problem


1 Answers

I have dealt with something similar before. Below is the solution I came up with. I basically use list2env to push variables to either the global or function's local environment and I then source the function in the designated environment.

This can be quite useful especially when coupled with exists as shown in the example below which would allow you to keep your script stand-alone.

These two questions may also be of help: Source-ing an .R script within a function and passing a variable through (RODBC) How to pass command-line arguments when source() an R file

# Function ----------------------------------------------------------------
subroutine <- function(file, param = list(), local = TRUE, ...) {
  list2env(param, envir = if (local) environment() else globalenv())
  source(file, local = local, ...)
}


# Example -----------------------------------------------------------------
# Create an example script
tmp <- "test_subroutine.R"
cat("if (!exists('msg')) msg <- 'no argument provided'; print(msg)", file = tmp)

# Example of using exists in the script to keep it stand-alone
subroutine(tmp)

# Evaluate in functions environment
subroutine(tmp, list(msg = "use function's environment"), local = TRUE)
exists("msg", envir = globalenv()) # FALSE

# Evaluate in global environment
subroutine(tmp, list(msg = "use global environment"), local = FALSE)
exists("msg", envir = globalenv()) # TRUE

unlink(tmp)
like image 75
Raad Avatar answered Sep 14 '25 04:09

Raad