Skip to content

Instantly share code, notes, and snippets.

@smbache
Created June 26, 2014 08:08
Show Gist options
  • Save smbache/86fe703fa46e39df33ea to your computer and use it in GitHub Desktop.
Save smbache/86fe703fa46e39df33ea to your computer and use it in GitHub Desktop.
Fun with pipe and armed expressions
#' 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
@rdinnager
Copy link

I think

eval(call("%>%", lhs, rhs), parent, parent)

should be:

eval(call("%>%", lhs, substitute(rhs)), parent, parent)

At least it didn't work properly for me when the rhs had more than one argument until I changed this.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment