Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Source only part of a file

My R workflow is usually such that I have a file open into which I type R commands, and I’d like to execute those commands in a separately opened R shell.

The easiest way of doing this is to say source('the-file.r') inside R. However, this always reloads the whole file which may take considerable time if big amounts of data are processed. It also requires me to specify the filename again.

Ideally, I’d like to source only a specific line (or lines) from the file (I’m working on a terminal where copy&paste doesn’t work).

source doesn’t seem to offer this functionality. Is there another way of achieving this?

like image 341
Konrad Rudolph Avatar asked Aug 31 '12 12:08

Konrad Rudolph


People also ask

What does it mean to source the file?

When a file is sourced (by typing either source filename or . filename at the command line), the lines of code in the file are executed as if they were printed at the command line. This is particularly useful with complex prompts, to allow them to be stored in files and called up by sourcing the file they are in.

What is sourcing a file in R?

Description. source causes R to accept its input from the named file or URL or connection or expressions directly. Input is read and parse d from that file until the end of the file is reached, then the parsed expressions are evaluated sequentially in the chosen environment.

What does it mean to source a file in Linux?

In Linux systems, source is a built-in shell command that reads and executes the file content in the current shell. These files usually contain a list of commands delivered to the TCL interpreter to be read and run.


1 Answers

Here's another way with just R:

source2 <- function(file, start, end, ...) {
    file.lines <- scan(file, what=character(), skip=start-1, nlines=end-start+1, sep='\n')
    file.lines.collapsed <- paste(file.lines, collapse='\n')
    source(textConnection(file.lines.collapsed), ...)
}
like image 168
Matthew Plourde Avatar answered Sep 21 '22 14:09

Matthew Plourde