Last active
February 15, 2018 16:42
-
-
Save Selbosh/dd94b137dcf987b12ce19c1d023f2ffb to your computer and use it in GitHub Desktop.
Kolmogorov–Smirnov tests with non-standard evaluation
This file contains 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
library(rlang) | |
library(dplyr) | |
# ---------------------------------------------------------------- | |
# First implementation: specify desired variable names explicitly. | |
# ---------------------------------------------------------------- | |
test1 <- function(var1, var2, data, name1, name2) { | |
qvar1 <- enquo(var1) | |
qvar2 <- enquo(var2) | |
assign(name1, pull(data, !!qvar1)) | |
assign(name2, pull(data, !!qvar2)) | |
substitute( | |
expr = ks.test(x, y), | |
env = list(x = as.name(name1), | |
y = as.name(name2)) | |
) %>% eval | |
} | |
# ------------------------------------------------------------------- | |
# EXAMPLES 1 | |
# ------------------------------------------------------------------- | |
test1(Petal.Width, Petal.Length, iris, 'fred', 'george') | |
## Two-sample Kolmogorov-Smirnov test | |
## | |
## data: fred and george | |
## D = 0.66667, p-value < 2.2e-16 | |
## alternative hypothesis: two-sided | |
# ------------------------------------------------------------------- | |
# Second implementation: use original column names by default. | |
# ------------------------------------------------------------------- | |
test2 <- function(var1, var2, data, | |
name1 = NULL, name2 = NULL) { | |
qvar1 <- enquo(var1) | |
qvar2 <- enquo(var2) | |
if (!is.null(name1)) { | |
assign(name1, pull(data, !!qvar1)) | |
x_name <- as.name(name1) | |
} else { | |
assign(deparse(substitute(var1)), pull(data, !!qvar1)) | |
x_name <- as.name(deparse(substitute(var1))) | |
} | |
if (!is.null(name2)) { | |
assign(name2, pull(data, !!qvar2)) | |
y_name <- as.name(name2) | |
} else { | |
assign(deparse(substitute(var2)), pull(data, !!qvar2)) | |
y_name <- as.name(deparse(substitute(var2))) | |
} | |
substitute( | |
expr = ks.test(x, y), | |
env = list(x = x_name, | |
y = y_name) | |
) %>% eval | |
} | |
# ------------------------------------------------------------------- | |
# EXAMPLES 2 | |
# ------------------------------------------------------------------- | |
test2(Petal.Width, Petal.Length, iris) | |
## Two-sample Kolmogorov-Smirnov test | |
## | |
## data: Petal.Width and Petal.Length | |
## D = 0.66667, p-value < 2.2e-16 | |
## alternative hypothesis: two-sided | |
test2(Petal.Width, Petal.Length, iris, 'fred', 'george') | |
## Two-sample Kolmogorov-Smirnov test | |
## | |
## data: fred and george | |
## D = 0.66667, p-value < 2.2e-16 | |
## alternative hypothesis: two-sided |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment