Non-Standard Evaluation (NSE hereafter) occurs when R expressions are
captured and evaluated in a manner different than if they had been
executed without intervention. subset
is a canonical
example, which we use here with the built-in iris
data
set:
subset(iris, Sepal.Width > 4.1)
## Sepal.Length Sepal.Width Petal.Length Petal.Width Species
## 16 5.7 4.4 1.5 0.4 setosa
## 34 5.5 4.2 1.4 0.2 setosa
Sepal.Width
does not exist in the global environment,
yet this works because subset
captures the expression and
evaluates it within iris
.
A limitation of NSE is that it is difficult to use programmatically:
<- quote(Sepal.Width > 4.1)
exp.a subset(iris, exp.a)
## Error in subset.data.frame(iris, exp.a): 'subset' must be logical
oshka::expand
facilitates programmable NSE, as with this
simplified version of subset
:
<- function(x, subset) {
subset2 <- expand(substitute(subset), x, parent.frame())
sub.exp <- eval(sub.exp, x, parent.frame())
sub.val !is.na(sub.val) & sub.val, ]
x[
}subset2(iris, exp.a)
## Sepal.Length Sepal.Width Petal.Length Petal.Width Species
## 16 5.7 4.4 1.5 0.4 setosa
## 34 5.5 4.2 1.4 0.2 setosa
expand
is recursive:
<- quote(Species == 'virginica')
exp.b <- quote(Sepal.Width > 3.6)
exp.c <- quote(exp.b & exp.c)
exp.d
subset2(iris, exp.d)
## Sepal.Length Sepal.Width Petal.Length Petal.Width Species
## 118 7.7 3.8 6.7 2.2 virginica
## 132 7.9 3.8 6.4 2.0 virginica
We abide by R semantics so that programmable NSE functions are almost identical to normal NSE functions, with programmability as a bonus.
oshka
,
including a brief comparison to rlang
.oshka
in which we recreate simplified
versions of dplyr
and data.table
that
implement programmable NSE with oshka::expand
.This package is proof-of-concept. If it elicits enough interest we will re-write the internals in C and add helper functions for common use patterns.
install.packages('oshka')
# or development version
::instal_github('brodieg/oshka@development') devtools
Feedback is welcome, particularly if you are aware of some NSE pitfalls we may be ignoring.
Brodie Gaslam is a hobbyist programmer based on the US East Coast.
The name of this package is derived from “matryoshka”, the Russian nesting dolls.