Skip to content

Instantly share code, notes, and snippets.

@wjhopper
Created May 9, 2017 19:55
Show Gist options
  • Save wjhopper/6421790c02b83ec7e9fad4b47142a834 to your computer and use it in GitHub Desktop.
Save wjhopper/6421790c02b83ec7e9fad4b47142a834 to your computer and use it in GitHub Desktop.
Examining R's Non-Standard Evaluation Behavior with subscramble
library(pryr)
sample_df <- data.frame(a = 1:5, b = 5:1, c = c(5, 3, 1, 4, 1))
scramble <- function(x) x[sample(nrow(x)), ]
subset1 <- function(x, cond) {
condition_call <- substitute(cond)
r <- eval(condition_call, x, parent.frame())
x[r, ]
}
## Doesn't Work
subscramble1 <- function(x, condition) {
scramble(subset1(x, condition))
}
## Works
subset2_q <- function(x, condition) {
r <- eval(condition, x, parent.frame())
x[r, ]
}
subset2 <- function(x, condition) {
subset2_q(x, substitute(condition))
}
subscramble2 <- function(x, condition) {
condition <- substitute(condition)
scramble(subset2_q(x, condition))
}
subscramble1(sample_df, a >= 3)
subscramble2(sample_df, a >= 3)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment