I would like to "break" out of a pipe (and function) based on a conditional statement. There is a similar question here although it only evaluates a conditional in the middle of a pipe (i.e. without a return).
library(dplyr)
fnx <- function(data, val) {
data %>%
filter(mpg < val) %>%
{if(nrow(.) == 0) return(NA) else .} %>%
arrange(mpg)
}
fnx(mtcars, 22)
#works as expected since the conditional evaluates to FALSE
fnx(mtcars, 10)
#continues to run the pipe despite the fact that the
#conditional is TRUE resulting in "Error in UseMethod("arrange_") :
#no applicable method for 'arrange_' applied to an object of class "logical""
Any help would be greatly appreciated!
> sessionInfo()
R version 3.4.3 (2017-11-30)
Platform: x86_64-apple-darwin15.6.0 (64-bit)
Running under: macOS High Sierra 10.13.3
Matrix products: default
BLAS: /Library/Frameworks/R.framework/Versions/3.4/Resources/lib/libRblas.0.dylib
LAPACK: /Library/Frameworks/R.framework/Versions/3.4/Resources/lib/libRlapack.dylib
locale:
[1] en_US.UTF-8/en_US.UTF-8/en_US.UTF-8/C/en_US.UTF-8/en_US.UTF-8
attached base packages:
[1] stats graphics grDevices utils datasets methods base
other attached packages:
[1] bindrcpp_0.2 dplyr_0.7.4
loaded via a namespace (and not attached):
[1] compiler_3.4.3 httr_1.3.1 magrittr_1.5 assertthat_0.2.0
[5] R6_2.2.2 rgeolocate_1.0.1 pillar_1.1.0.9000 glue_1.2.0
[9] tibble_1.4.2 curl_3.1 Rcpp_0.12.15 jsonlite_1.5
[13] pkgconfig_2.0.1 rlang_0.2.0 bindr_0.1