Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

R pipe does not stop when triggering error

Tags:

r

magrittr

I've created this demo pipeline:

library(magrittr)
fun1 <- function(x) {
  cat("hello1")
}

fun2 <- function(x) {
  stop("stop %>% here!")
}

fun3 <- function(x) {
  cat("hello3")
}

5 %>% fun1() %>% fun2() %>% fun3()

> `hello3`

I'm quite confused about two things:

a) why only hello3 is printed and not hello1?

b) what is even more confusing is that fact that even fun2() produces an error, fun3 will still be called. I thought that stop in R triggers an execution error and without any catching mechanism this is going to produce the stop of the script.

Could someone explain me why this seems not to hold when using %>%. How can I ensure that the pipe stops if some function call produces an error?

like image 446
Ai4l2s Avatar asked Oct 22 '25 10:10

Ai4l2s


1 Answers

fun2() (and fun1()) are not called because x argument of fun3() is not used in the function and thus not evaluated. Try rewriting that pipeline with nested calls:

library(magrittr)
fun1 <- function(x) {
  cat("hello1")
}

fun2 <- function(x) {
  stop("stop %>% here!")
}

fun3 <- function(x) {
  cat("hello3")
}

# -------------------------------------------------------------------------

fun1(5)
#> hello1

fun2(fun1(5))
#> Error in fun2(fun1(5)): stop %>% here!

fun3(fun2(fun1(5)))
#> hello3

And now, let's put argument x into some use and try again:

fun3x <- function(x) {
  cat("hello3",x)
}

5 %>% fun1() %>% fun2() %>% fun3x()
#> Error in fun2(.): stop %>% here!

You might also want to check lazy evaluation in the functions chapter of Advanced R

In R, function arguments are lazily evaluated: they’re only evaluated if accessed.

like image 82
margusl Avatar answered Oct 24 '25 01:10

margusl



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!