return()
inside a magrittr pipeline does not actually execute return()
like you'd expect: \(x) { x %>% return(); FALSE }
will return FALSE
!
It will technically work "as expected" if this is the final statement
in the function body, but such usage is misleading. Instead, assign
the pipe outcome to a variable and return that.
See also
linters for a complete list of linters available in lintr.
Examples
# will produce lints
lint(
text = "function(x) x %>% return()",
linters = pipe_return_linter()
)
#> <text>:1:19: warning: [pipe_return_linter] Avoid return() as the final step of a magrittr pipeline. Instead, assign the output of the pipeline to a well-named object and return that.
#> function(x) x %>% return()
#> ^~~~~~~~
# okay
code <- "function(x) {\n y <- sum(x)\n return(y)\n}"
writeLines(code)
#> function(x) {
#> y <- sum(x)
#> return(y)
#> }
lint(
text = code,
linters = pipe_return_linter()
)
#> ℹ No lints found.