I'm not sure if this is even possible, but I'm looking for something similar to defining regions in R script. I would like to execute a pre-specified set of lines from another R script. I know I can run the entire file using source(filename)
but instead of running the entire file, I would like to only run a few lines in the file.
Is it possible for me to define regions
or anything similar in the file and then execute it from another file?
Any help would be much appreciated.
You can execute R script as you would normally do by using the Windows command line. If your R version is different, then change the path to Rscript.exe. Use double quotes if the file path contains space.
R file from another . R file, you can call the source("abc. R") followed by source("xyz. R") (assuming that both these files are in your current working directory.
There are three ways to execute multiple lines from within the editor: Select the lines and press the Ctrl+Enter key (or use the Run toolbar button); or. After executing a selection of code, use the Re-Run Previous Region command (or its associated toolbar button) to run the same selection again.
To execute one specific line: we simply click into the line we would like to execute and press the button with the green arrow ("execute current line or selection; or CTRL+ENTER ). RStudio will copy this line into the R console and execute the line (as if we would enter the command and press enter).
If you're worried about the region of interest will be shifted once you add new lines upstream, then an alternative (or slightly modified) version of MrFlick's answer would be read as:
sourcePartial <- function(fn,startTag='#from here',endTag='#to here') {
lines <- scan(fn, what=character(), sep="\n", quiet=TRUE)
st<-grep(startTag,lines)
en<-grep(endTag,lines)
tc <- textConnection(lines[(st+1):(en-1)])
source(tc)
close(tc)
}
Now you need to put a small, unique hash tag just above and below of the region of interest. Such as "#from here" and "#to here"
This doesn't sound like a super-safe idea given how easily line numbers can change during edits. Seems like it would be safest to split up your larger sourced file into smaller parts that are safer to include and run. But you could do something like this
sourcePartial <- function(fn, skip=0, n=-1) {
lines <- scan(fn, what=character(), sep="\n", skip=skip, n=n, quiet=TRUE)
tc <- textConnection(lines)
source(tc)
close(tc)
}
here we use scan()
to read lines from a file. See the documentation for skip=
and n=
at ?scan
to see how to skip a certain number of lines and stop reading after a certain number. So
sourcePartial("test.R", 4, 11)
would run lines 5-15 from "test.R"
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With