324
324

Reputation: 724

Running specified lines of R code on command

Suppose I am working on line 700 of an R script, and I want to re-run lines 300-500 without scrolling way up. Is there an R function for this functionality?

Upvotes: 1

Views: 647

Answers (1)

Allan Cameron
Allan Cameron

Reputation: 174586

If you are working in R studio, you can use the following function:

run_lines <- function(x) {
  editor <- rstudioapi::getSourceEditorContext()
  start <- rstudioapi::document_position(min(x), 1)
  end <- rstudioapi::document_position(max(x) + 1, 1)
  range <- rstudioapi::document_range(start, end)
  rstudioapi::setSelectionRanges(range, editor$id)
  selection <- rstudioapi::primary_selection(
    rstudioapi::getSourceEditorContext())$text
  source(textConnection(selection))
}

Then, suppose I have the following source file open as the active document in my editor window:

x <- 1
y <- 2
print(x + y)

print("hello world")

a <- 3
b <- 5
print(a + b)

If I want to run only lines 5 to 9, I can type in the console:

run_lines(5:9)
#> [1] "hello world"
#> [1] 8

Or, if I just want to run the first 3 lines, I can do:

run_lines(1:3)
#> [1] 3

Upvotes: 1

Related Questions