-
-
Save smbache/86fe703fa46e39df33ea to your computer and use it in GitHub Desktop.
Fun with pipe and armed expressions
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#' Arm a value with a function which fires when evaluated. | |
#' | |
#' @param expr an expression | |
#' @param fun a function of one argument. | |
#' | |
#' @return an expression which when evaluated returns the result of expr, | |
#' after evaluating fun(expr). | |
arm <- function(expr, fun) | |
{ | |
substitute({ | |
expr %T>% fun | |
}, | |
list( | |
fun = substitute(fun), | |
expr = substitute(expr) | |
) | |
) | |
} | |
#' replace pipe_with without messing with magrittr:::pipe/`%>%` itself. | |
#' | |
#' @param expr som expression, e.g. using compose, %,%, or simply a function. | |
pipe_with <- function(expr) function(lhs, rhs) | |
{ | |
parent <- parent.frame() | |
lhs <- eval(call("arm", substitute(lhs), expr), parent, parent) | |
eval(call("%>%", lhs, rhs), parent, parent) | |
} | |
#' Construct an armed pipe | |
`%a>%` <- pipe_with( | |
sum(., na = TRUE) %,% | |
cat("SUM:", ., "\n") | |
) | |
#' Try it out: | |
1:10 %a>% sin %a>% cos |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
I think
should be:
At least it didn't work properly for me when the rhs had more than one argument until I changed this.