Run a set of lines from another R file

I'm not sure if this is possible, but I'm looking for something similar to defining areas in an R script. I would like to execute a predefined rowset from another R script. I know that I can run the entire file using source(filename) , but instead of running the whole file, I would like to run only a few lines in the file.

Is it possible to define regions or something similar in a file and then execute it from another file?

Any help would be greatly appreciated.

+5
source share
2 answers

If you are worried that the area of ​​interest will be shifted after adding new lines up, then an alternative (or slightly modified) version of MrFlick's answer will 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 place a small, unique hash tag just above and below the area of ​​interest. For example, "# here from here" and "# here"

+10
source

This doesn't seem like a super safe idea, given how easily line numbers can change during editing. It seems like it would be safer to split your larger 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= in ?scan to see how to skip a certain number of lines and stop reading after a certain number. So

 sourcePartial("test.R", 4, 11) 

will run lines 5-15 from "test.R"

+3
source

Source: https://habr.com/ru/post/1204214/


All Articles