Skip to content

Instantly share code, notes, and snippets.

@hadley
Created October 12, 2012 17:55
Show Gist options
  • Save hadley/3880527 to your computer and use it in GitHub Desktop.
Save hadley/3880527 to your computer and use it in GitHub Desktop.
subset deconstruction
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