Some Fun With User/Package Level Pipes/Anonymous-Functions

[This article was first published on R – Win Vector LLC, and kindly contributed to R-bloggers]. (You can report issue about the content on this page here)
Want to share your content on R-bloggers? click here if you have a blog, or here if you don't.

In addition to adding a base-R pipe it appears a new base-R function builders is in the works (in addition to “function”).

R is a very versatile language, with a great ability to accept user-level or package extensions. What I mean by this is, user code and package code (which have about the same level of privilege) can control quite a lot. A pretty graceful pipe and function builder can in fact already be written in R itself.

For brevity I’ll demonstrate this using package code (so we don’t have to see all the details).

Let’s try and build a new anonymous function builder other than function.

library(wrapr)  # attach the wrapr package
defineLambda()  # add λ function builder to workspace

f <- λ(x, x + 1)  # define a function that adds one
f(2)  # use it
# [1] 3

Now we can pipe into such a function.

3 %.>% f
# [1] 4

And we can pipe directly into the anonymous function definition if we add the argument placeholder.

4 %.>% λ(x, x + 1)(.)
[1] 5

At first it appears we can’t pipe into the definition without the placeholder.

5 %.>% λ(x, x + 1)
# function (x) 
# x + 1

However, can solve this with bquote-style argument escaping.

6 %.>% .(λ(x, x + 1))
# [1] 7

Or even by setting an attribute on the function builder.

attr(λ, 'dotpipe_eager_eval_function') <- TRUE

7 %.>% λ(x, x + 1)
# [1] 8

This controlled effect is due the wrapr-dot-pipe treating the incoming argument as a value and using R’s existing S3 and S4 type systems to control pipe behavior. This is the power of leaving control in the hands of the users and packages, we can specify what behavior we expect from the function builder to our taste.

To leave a comment for the author, please follow the link and comment on their blog: R – Win Vector LLC.

R-bloggers.com offers daily e-mail updates about R news and tutorials about learning R and many other topics. Click here if you're looking to post or find an R/data-science job.
Want to share your content on R-bloggers? click here if you have a blog, or here if you don't.

Never miss an update!
Subscribe to R-bloggers to receive
e-mails with the latest R posts.
(You will not see this message again.)

Click here to close (This popup will not appear again)