Abort code execution in R (-Studio)

I use RStudio to write code in R. I usually send large chunks of code, selecting it and clicking Ctrl + Enter. Now, when an error occurs (for example, the connection to the database cannot be established), I would like to stop executing the following code.

I tried stop(), which works when all the code is on the same line:

# 21 is not shown
42; stop("error"); 21;

But when the code spans multiple lines, the code is still evaluated:

# Here 21 is shown
42
stop("error")
21

Is there a way to abort code when sending large code snippets?

+4
source share
2 answers

You can wrap your code between {}(curly braces) as they are pretty much equivalent to your chain ;.

{
  42
  stop("error")
  21
}
## Error: error

, .

do <- get("{")
do(x <- 3, y <- 2*x-3, 6-x-y)
## [1] 0
x <- 3; y <- 2*x-3; 6-x-y
## [1] 0
+4

@DavidArenburg - , , . , , Ctrl-Enter RStudio. , :

  • , print

.

{
  print(42)
  stop("error")
  print(21)
}

#[1] 42
# Error: error
  1. :

.

block <- function(expr) {
  expr <- substitute(expr)
  for (i in seq(expr)[-1]) {
    y <- withVisible(eval(expr[[i]], parent.frame()))
    if (y$visible && i != length(expr)) print(y$value)
  }
  y$value
}

block({
  42
  stop("error")
  21
})

#[1] 42
# Error in eval(expr, envir, enclos) : error

, , .

.

.

microbenchmark::microbenchmark(block = block({
  a <- 1:1e6
  b <- rnorm(1e6)
  sum(a + b)
}), curly = {
  a <- 1:1e6
  b <- rnorm(1e6)
  sum(a + b)
})

#Unit: milliseconds
#  expr      min       lq     mean   median       uq      max neval
# block 108.7961 130.2517 169.4891 176.8425 197.4749 299.4014   100
# curly 109.9183 134.3076 171.9430 174.7121 194.5748 292.5958   100
+2

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


All Articles