Reputation: 823
Is there a way in R to pass the values of some variables, say strings, defined in a script to another script that is being sourced so that the latter can use them without having to declare them? Eg:
some R code
...
...
var1 <- "some string"
var2 <- "some param"
source("header.r")
Within header.r
a list()
has the slots with the names of the strings in var1 and var2:
tabl <- alldata.list[["some string"]][["some param"]]
Such that when I run the original script and call the header, tabl
will be addressed properly?
Additionally, is there a restriction on the number and type of elements that can be passed?
Upvotes: 1
Views: 1625
Reputation: 60944
When you use source
to load a .R
file, this sequentially runs the lines in that script, merging everything in that script into your running R session. All variables and functions are available from that moment onwards.
To make your code more readable/maintainable/debuggable though I would recommend not using variables to communicate between source files. In stead, I would use functions. In practice for me this means that I have one or multiple files which contain helper functions (sort of a package-light). These helper functions abstract away some of the functionality you need in the main script, making it shorter and more to-the-point. The goal is to create a main script that roughly fills a screen. In this way you can easily grasp the main idea of the script, any details can be found in the helper functions.
Using functions makes the main script self contained and not dependent on what happens in executable code in other source files. This requires less reasoning by yourself and others to determine what the script is exactly doing as you basically just have to read 40-50 lines of code.
Upvotes: 4