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?
fun2()(andfun1()) are not called becausexargument offun3()is not used in the function and thus not evaluated. Try rewriting that pipeline with nested calls:And now, let's put argument
xinto some use and try again:You might also want to check lazy evaluation in the functions chapter of Advanced R