Created
October 12, 2012 17:55
-
-
Save hadley/3880527 to your computer and use it in GitHub Desktop.
subset deconstruction
This file contains hidden or 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
SUBSET2 <- function(dat, ex) { | |
ex <- substitute(ex) | |
frames <- rev(sys.frames()) | |
for(f in frames) { | |
message("---------------------------------------------") | |
cat("Vars: ", paste(ls(f), sep = ","), "\n") | |
call <- substitute(substitute(x, f), list(x = ex)) | |
ex <- eval(call) | |
cat("Expr: ", deparse(ex), "\n") | |
} | |
dat[eval(ex, dat, parent.frame()),] | |
} | |
# In most circumstances it works ok | |
SUBSET2(mtcars, cyl == 4)$cyl | |
x <- 4 | |
SUBSET2(mtcars, cyl == x)$cyl | |
# But because it evaluates in every frame, it's possible to | |
# create situations that don't work | |
f <- function() { | |
cyl <- 4 | |
g() | |
} | |
g <- function() { | |
SUBSET2(mtcars, cyl == 4)$cyl | |
} | |
f() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment