Created
March 12, 2019 15:09
-
-
Save brodieG/2fe732b3b53086e2dad19b0633887690 to your computer and use it in GitHub Desktop.
Test out let with LM
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
## Tests based on https://mailund.dk/posts/scoping-rules-and-nse/ | |
# rm(list=ls()) | |
if(length(ls())) message("you have variables defined in the environment") | |
library(wrapr) | |
lm_prop2a <- function(x, y, d, prop, eval) { | |
let(c(x = x, y = y, prop = prop, d=d), | |
summary(lm(y ~ x, data = d))$prop, | |
eval = eval, envir=parent.frame()) | |
} | |
indirect2a <- function(xx, yy, eval) { | |
d <- data.frame(x = xx, y = yy) | |
lm_prop2a("x", "y", "d", "residuals", eval = eval) | |
} | |
## First set of tests | |
set.seed(42) | |
d1 <- data.frame(x = rnorm(5), y = rnorm(5)) | |
d2 <- data.frame(a = rnorm(5), b = rnorm(5)) | |
xx <- rnorm(5) | |
(res <- lm_prop2a("x", "y", "d1", "residuals", eval = TRUE)) | |
stopifnot(identical(res, summary(lm(y ~ x, d1))$residuals)) | |
(res <- lm_prop2a("xx", "y", "d1", "residuals", eval = TRUE)) | |
stopifnot(identical(res, summary(lm(y ~ xx, d1))$residuals)) | |
(res <- lm_prop2a("a", "b", "d2", "residuals", eval = TRUE)) | |
stopifnot(identical(res, summary(lm(b ~ a, d2))$residuals)) | |
(res <- lm_prop2a("xx", "b", "d2", "residuals", eval = TRUE)) | |
stopifnot(identical(res, summary(lm(b ~ xx, d2))$residuals)) | |
## Second set | |
x <- a <- xx | |
(res <- lm_prop2a("a", "y", "d1", "residuals", eval = TRUE)) | |
stopifnot(identical(res, summary(lm(y ~ a, d1))$residuals)) | |
(res <- lm_prop2a("x", "b", "d2", "residuals", eval = TRUE)) | |
stopifnot(identical(res, summary(lm(b ~ x, d2))$residuals)) | |
## Last set | |
aa <- rnorm(5) ; bb <- rnorm(5) | |
(res <- indirect2a(aa, bb, eval = TRUE)) | |
stopifnot(identical(res, summary(lm(bb ~ aa))$residuals)) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment