skip to main content
R Plugin Event
The R Plugin event allows scripts in the R programming language to be executed as a post-processing event in a study.
Note:  For you to use the R Plugin event, the R Project for Statistical Computing must be installed on your computer; see Install R and Component Packages for details. This event was developed and tested with R version 3.0.2, but it should work with newer versions of R.
To configure an R Plugin event, you specify an R script file and a function within the R script file. You can also specify arguments to pass to the function. When the R  Plugin event is executed, it calls the function and passes the defined arguments. See R Function frame and Arguments frame for details.
There are no formal restrictions on the user-defined R functions that can be called. However, the R Plugin event does provide utilities that assist in integrating post-processing outputs from R into the general RiverSMART file management framework. This is done by providing predefined arguments that pass information such as scenario names, linked input files, and output file locations.
Note:  In this section, the term input files refers to files that are inputs to the R Plugin event. These files are outputs from previous events in the study, such as a RiverWare event or an RDF To Excel event. See Predefined Arguments for details.
Using the R Plugin Event
You can add an R Plugin event to the post-processing of scenario data in RiverSMART. When the event is executed, it runs a user-defined R script in the background.
The file types defined and used in post-processing—RDFs and Excel workbooks—can be linked to the R Plugin event as input files. The user’s R script is responsible for processing the data provided in the input files. The R Plugin event is not linkable in the interface to any files on its output side; that is, the R Plugin event is the terminus of its post-processing stream. However, there is no limit to the number of R Plugin events in a study; each as its own terminus.
RiverSMART provides an output folder as an optional predefined argument to the event. The user’s R script can use this specified output folder as a location to save any files generated by the R code, but RiverSMART does not link these files into subsequent processes. Though RiverSMART does not force files generated by the R code to be saved in the predefined output folder, for the following reasons, it is recommended that R scripts called from RiverSMART be written to save all output files to this location.
• The predefined output folder guarantees that R output files are saved in a file structure consistent with the general RiverSMART file management framework.
• Writing files to another location in the RiverSMART folder structure may result in file-naming conflicts or the unintentional deletion of output files if RiverSMART clears a folder of its contents as part of the re-execution of a portion of a study.
Using an R Plugin Event Outside of RiverSMART
Following is the process for using an R Plugin event outside of RiverSMART.
1. Install R; see Install R and Component Packages for details.
2. Create an R script. This script must contain, at a minimum, a single user-defined function that matches the function named in the R Plugin event configuration. The script can contain additional commands before or after the function definition. These commands are executed when the script is sourced from the RiverSMART-generated R script, but RiverSMART only passes arguments for the single function call; see RiverSMART-generated R Script for details.
The user-defined R script is responsible for all processing of data, including reading the data from the input files. The script can use any R functionality, including sourcing other script files, calling other functions, or reading data from files outside the RiverSMART folder structure.
Using an R Plugin Event Within RiverSMART
Following is the process for using an R Plugin event withing RiverSMART.
1. Add an R Plugin event to the workspace.
2. Link input files. These are one or more RDF files or Excel workbooks on the RiverSMART workspace that are outputs from another RiverSMART event; see Linking Files for details.
3. Specify an R script; see R Function frame for details.
4. Specify an R function; see R Function frame for details.
5. Specify arguments and their values; see Arguments frame for details.
6. Specify how to process scenarios; see Scenario Processing frame for details.
7. Generate and simulate scenarios, if not done previously.
8. Post-process scenarios.
Linking Files
RDF and Excel workbooks can be linked to the R Plugin event as input files. Multiple input files can be linked to a single R Plugin event, and a single input file can be linked to multiple R Plugin events. The event is not linkable in the interface to any files on its output side; that is, the R Plugin event is the terminus of its post-processing stream.
The linked input files are used by RiverSMART to define the values of the <linked input file paths> and <linked input file names> predefined arguments; see Predefined Arguments for details.
R Plugin Event Configuration Window
This window opens when you open an R Plugin event on the RiverSMART workspace.
Name
Enter a user-defined unique name for the R Plugin event.
R Function frame
In this frame, you specify the R script file and function.
File
Specify the R script file. The R Plugin event creates its own R script file that sources this user-specified script file when the event is executed; see RiverSMART-generated R Script for details.
Enter the folder path in the text box, or select Select and select the folder through the File Chooser.
Function
Specify a function from the R script file. This function allows the R Plugin event to pass user-specified arguments to the R script. The event calls the function after sourcing the R script file; see RiverSMART-generated R Script for details.
Note:  It is the user's responsibility to write an R script and function that use proper R syntax. There are no limits to what can be included in the script, other than it must include the specified function and the function must accept the arguments specified in the R Plugin Configuration window. The user-created R script can source other files, call other functions, or require any installed R packages. See Install R and Component Packages for details.
If you need to view the script file to find the function, select Preview to view the script file in a separate window.
Arguments frame
In this frame, you define arguments and their values.
Pass Arguments By
Select the option for how arguments are to be passed.
• Name. Arguments are passed by name. You must specify a name for each argument in the R Plugin configuration that exactly matches the name in the function definition in the R script. In this case, the order of arguments in the R Plugin configuration does not matter.
Note:  This option is recommended.
• Position. Arguments are passed by position. You do not specify names for arguments. Instead, each argument is given an index number identifying its position in the list of arguments. In this case, the order of the arguments in the R Plugin configuration must match the order of the arguments in the function definition.
Argument list
To add a new argument to the list, select Plus. To remove a selected argument, select Minus. To adjust the order of arguments in the configuration, select an argument, then select the Up or Down arrows, as appropriate.
Edit frame
In this frame, you define details for each argument in the list. It is made available when you add or select an argument on the list.
Name
Available only if the Pass Arguments by Name option is selected. Enter a user-defined name for the argument. This can be any valid name in the R programming language. All alphanumeric symbols are allowed plus ‘.’ and ‘_’, with the restriction that the name must start with ‘.’ or a letter, and if it starts with ‘.’ the second character must not be a digit.
Class
Select the argument class, as follows. This selection determines the remaining options.
• User Defined. The argument is user-defined. You must specify values in the Type, Description, and Value fields; see User-defined Arguments below for details.
• Predefined. The argument is predefined, and the value is determined at run time. You must specify an Argument option; see Predefined Arguments for details.
User-defined Arguments
The following fields are available only if the User Defined option is selected.
See
Type
Select the argument type. This must match the type expected by the user function called by the R Plugin event.
Options are as follows.
• Numeric. A numeric argument passes a double-precision vector of values; the vector may have a length of 1. The following figures show possible valid entries for numeric argument values.
• Integer. An integer argument is the same as a numeric type, but any digits after a decimal point are truncated; that is, all values are rounded down to the nearest whole number. For example, a value entered as “12.75” is passed to the R function as “12”.
• Character. A character argument allows a character string or a vector of character strings to be passed. The following figures show possible valid entries for character argument values.
Quotation marks are optional; their use has no effect on the result. For example, the characterVector definition, with quotation marks, in the previous figure produces the same result as the characterVector definition, without quotation marks, in the following figure.
• Logical. A logical argument passes either TRUE or FALSE. When you select this argument type, you must set the value for the argument by selecting either TRUE or FALSE. A logical argument cannot contain multiple values.
• R Expression. This argument is generic and can contain any valid R expression. Technically, any of the previous arguments can be defined as an R expression argument, but this type also allows commands that are part of the R programming language to be passed as an argument value. For example, a vector of a single value repeated 10 times may be passed through an R expression argument using the R rep() function.
Note:  It is the user’s responsibility to ensure that valid R syntax is used to specify the R expression argument.
Note:  It is possible to use other previously defined arguments in an R expression. For example, if a previous argument is of type Integer with name N and value 10, the expression for the repeatYears argument shown in the following figure can be written as follows.
rep(2015, N)
• Function Name. The name of a function is passed as an argument to the function being called by the R Plugin event. For example, in one season, values may be processed using one method, but other seasons may use a different method. No arguments are passed in the function name argument; only the function name is passed.
The specified function can be either user-defined or predefined in the R programming language. For a user-defined function, you must ensure the function is defined in the script. For a predefined R function, you must ensure any required packages are loaded by the script.
Description
Enter an optional argument description. This is for your reference only.
Value
Enter the argument value. Values for numeric, integer and character arguments can either be a single value or a vector with the individual elements separated by commas.
Note:  You do not need to enter the R concatenate command, c(...), for a vector of values; only the commas separating the values are required. The R Plugin event requires a value to be specified for each argument in the list.
Predefined Arguments
The following fields are available only if the Predefined option is selected.
Argument
Select a predefined argument. The value of the argument to be passed is determined at runtime, so the menu options show the generic argument value.
Options are as follows. See Example 5.1 for sample values that might be passed in a simple study.
• <scenario names>. If the Scenario Processing By Scenario Sets option is selected, this argument matches the scenarios defined by the selected scenario set. If the Scenario Processing By Scenarios option is selected, this argument is a single scenario name each time it is passed.
• <number of scenarios>. This argument is an integer equal to the length of the <scenario names> argument.
• <linked input directory>. This argument is always the Study Folder specified in the main RiverSMART workspace, appended with the Scenario\ subfolder. The use of the term linked input indicates this folder includes files that are inputs to the R script. The <linked input directory> includes the raw RiverWare outputs—typically RDF files—or outputs from another RiverSMART event.
• <linked input file paths>. This argument allows the files to be fully specified for each scenario. The length of this character vector is calculated as follows:
<number of scenarios> * length(<linked input file names)
• <linked input file names>. This argument includes just the general file names, as displayed in the RiverSMART workspace. It does not include a separate element for each scenario.
• <output directory>. This argument specifies a file path where outputs from the R script can be saved. RiverSMART creates the folder but does nothing with this argument directly after passing it to R. If the Scenario Processing By Scenario Sets option is selected, <output directory> is the Study Folder specified in the main RiverSMART workspace, with the ScenarioSet\Scenario_Set_Name\R_Plugin_Name\ subfolder appended. If the Scenario Processing By Scenarios option is selected, <output directory> is the Study Folder with the Scenario\Scenario_Name\R_Plugin_Name\ subfolder appended.
It is the user’s responsibility to incorporate the <output directory> argument into R script commands that write output files; RiverSMART does nothing to enforce the use of this output location. For the following reasons, however, it is recommended that R scripts called from RiverSMART save all output files to this location.
• The predefined output folder guarantees R output files are saved in a file structure consistent with the general RiverSMART file management framework.
• Writing files to another location in the RiverSMART folder structure may result in file-naming conflicts or the unintentional deletion of output files if RiverSMART clears a folder of its contents as part of the re-execution of a portion of a study.
Example 5.1  Example values passed by predefined arguments
Assume the study has the following characteristics. The table lists possible values that might be passed by each predefined argument.
• Four supply and demand scenarios, consisting of the following.
– Two supply scenarios: Wet and Dry
– Two demand scenarios: HighDemand and LowDemand
• Two linked rdf files: UpperBasinOutput.rdf and LowerBasinOutput.rdf
• The scenarios are processed by a scenario set named “AllScenarios” that includes all four scenarios.
• The R Plugin event is named “BasinResultsR”.
 
Predefined argument
Sample value passed to R
<linked input directory>
“C:\users\UserName\RiverSMARTFiles\MyStudy\Scenario\”
<scenario names>
c(“Dry,HighDemand”, “Dry,LowDemand”, “Wet,HighDemand”, “Wet,LowDemand”)
<number of scenarios>
4
<linked input file names>
c("UpperBasinOutput.rdf", "LowerBasinOutput.rdf")
<linked input file paths>
c("C:\users\UserName\RiverSMARTFiles\MyStudy\Scenario\Dry,HighDemand\UpperBasinOutput.rdf",
"C:\users\UserName\RiverSMARTFiles\MyStudy\Scenario\Dry,HighDemand\LowerBasinOutput.rdf",
"C:\users\UserName\RiverSMARTFiles\MyStudy\Scenario\Dry,LowDemand\UpperBasinOutput.rdf",
...)
<output directory>
“C:\users\UserName\RiverSMARTFiles\MyStudy\ScenarioSet\AllScenarios\BasinResultsR\”
Type
Display only. All predefined arguments have the character type, with the exception of <number of scenarios>, which is an integer.
Description
Display only. Displays a description of the selected argument.
Value
Display only. Indicates the argument value is determined at run time.
Scenario Processing frame
In this frame, you select the method for processing scenarios.
By Scenarios
The R Plugin event is executed once for each scenario selected in the Scenario List Post-Processor window. To open this window, on the RiverSMART menu, select Scenarios, then Post-Process Scenarios and select the scenarios to be applied.
To execute the R Plugin event using this option, in the Scenario List Post-Processor window, select Scenarios, then Post-Process Checked Scenarios; this executes all post-processing events for the selected scenarios. If the R Plugin event uses the scenario_names predefined argument, its value is a single scenario name each time the R Plugin event is executed. The number_of_scenarios argument has a value of 1.
By Scenario Sets
The R Plugin event is executed once for each selected scenario set. When you select this option, all scenario sets defined in the study are listed in the frame, allowing you to select the scenario sets to be applied.
To execute the R Plugin event using this option, on the RiverSMART menu, select Scenarios, then R Plugin, then select the appropriate R Plugin event. If the R Plugin event uses the scenario_names predefined argument, it is a vector with the list of scenarios defined by the scenario set. The number_of_scenarios argument is equal to the length of that vector.
Error Handling and Log File
RiverSMART has no knowledge of the user-created R script and therefore does not report success or failure of the script execution. It is the user’s responsibility to verify that the R script executed successfully.
Note:  RiverSMART does not automatically delete old output files generated by your R script, so it is possible for old output files to exist if the R script fails on a current invocation. Therefore, it is important to check the time stamps on output files to verify they are from the current invocation.
RiverSMART creates a log file, which you can open in a text editor after the R Plugin event has executed. This is useful for verifying successful execution and identifying errors.
• If processing by Scenario Sets, the file is at the following location:
Study_Folder\Working\Plugin_Name\Scenario_Set_Name\RPlugin.log
• If post-processing by Scenarios, the file is at the following location:
Study_Folder\Working\Plugin_Name\Scenario_Name\RPlugin.log
Tip:  Use the button to get to the log file for the scenario set:
The log file includes all messages sent to R Standard Out and Standard Error. For an execution with no errors and no output messages, the only contents of the log file may be the following lines:
STANDARD OUT
STANDARD ERROR
If an error occurs during execution, messages are printed under STANDARD ERROR. Any print commands in the user’s script print to the STANDARD OUT in the log file.
RiverSMART-generated R Script
The R Plugin event creates an R script file, which is executed in the background by the R application each time the R Plugin event is invoked.
After the R Plugin event has executed, you can open the log file in a text editor. This is useful for debugging issues, when the R script does not execute as expected.
• If processing by Scenario Sets, the file is at the following location:
Study_Folder\Working\Plugin_Name\Scenario_Set_Name\RPlugin.R
• If processing by Scenarios, the file is at the following location:
Study_Folder\Working\Plugin_Name\Scenario_Name\RPlugin.R
If arguments are passed By Position, the RiverSMART-generated R Script has the following general form.
source(User-specified_R_file)
arg1 <- <value>
arg2 <- <value>
...
argN <- <value>
<UserSpecifiedFunction>(arg1, arg2, arg3, ..., argN)
If arguments are passed By Name, the commands assigning values to the arguments use the argument names specified in the R Plugin Configuration window. The final function call has the following form. Using this form, the order of arguments in the event may differ from the order in the function definition.
<UserSpecifiedFunction>(arg1 = arg1, arg2 = arg2, arg3 = arg3, ..., argN = argN)
The R script is sourced as the first command in the script; then arguments are assigned values; then the function is called.
This process allows you to include additional commands in the R script before the specified function is called. These can include additional function definitions, which are then used as R expression arguments in the event. This process also allows an argument to be used in the definition of another argument value further down the list. For example, the following list of arguments is valid.
Revised: 12/06/2024