As subset()
manual states:
Warning: This is a convenience function intended for use interactively
I learned from this great article not only the secret behind this warning, but a good understanding of substitute()
, match.call()
, eval()
, quote()
, ?call
, promise
and other related R subjects, that are a little bit complicated.
Now I understand what's the warning above for. A super-simple implementation of subset()
could be as follows:
subset = function(x, condition) x[eval(substitute(condition), envir=x),]
While subset(mtcars, cyl==4)
returns the table of rows in mtcars
that satisfy cyl==4
, enveloping subset()
in another function fails:
sub = function(x, condition) subset(x, condition)
sub(mtcars, cyl == 4)
# Error in eval(expr, envir, enclos) : object 'cyl' not found
Using the original version of subset()
also produces exactly the same error condition. This is due to the limitation of substitute()-eval()
pair: It works fine while condition
is cyl==4
, but when the condition
is passed through the enveloping function sub()
, the condition
argument of subset()
will be no longer cyl==4
, but the nested condition
in the sub()
body, and the eval()
fails - it's a bit complicated.
But does it exist any other implementation of subset()
with exactly the same arguments that would be programming-safe - i.e. able to evaluate its condition while it's called by another function?
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…