I'm trying to do some unit testing using the testthat
package but I can't seem to get it to work properly together with the rms
package. The following example:
library(rms)
set.seed(10)
ds <- data.frame(
ftime = rexp(200),
fstatus = sample(0:1,200,replace=TRUE),
x1 = runif(200),
x2 = runif(200),
x3 = factor(sample(LETTERS[1:3], size=200, replace=TRUE)))
ddist <- datadist(ds)
options(datadist="ddist")
s <- Surv(ds$ftime, ds$fstatus == 1)
fit <- cph(s ~ x1 + x2 + x3, data=ds)
returns this error:
Error in Design(eval.parent(m)) : dataset ddist not found for options(datadist=)
This even though print(ddist) works and the options("datadist") returns the proper variable. Does testthat
have a different variable scope that causes errors?
I run the testthat by a R console started in the my package dir (Eclipse StatET):
library(testthat)
test_dir("inst/tests")
q()
The same error occurs with the R CMD check --as-cran
While @agstudy's suggestion is correct I've figured out a simple workaround for the bug by using the <<- operator that assigns the variable to the global environment, here's a test-file that works:
set.seed(10)
n <- 11
ds <- data.frame(
y = rnorm(n),
x1 = factor(sample(c("a", "aa", "aaa"), size = n, replace = TRUE)))
suppressMessages(library(rms))
dd <<- datadist(ds)
options(datadist = "dd")
context("rms")
test_that("test", {
fit <- ols(y ~ x1, data=ds)
s <- summary(fit)
expect_true(inherits(s, "summary.rms"))
})
This works also if you happen to do the assignment within the test_that
:
context("rms")
test_that("test", {
set.seed(10)
n <- 11
ds <- data.frame(
y = rnorm(n),
x1 = factor(sample(c("a", "aa", "aaa"), size = n, replace = TRUE)))
suppressMessages(library(rms))
dd <<- datadist(ds)
options(datadist = "dd")
fit <- ols(y ~ x1, data=ds)
s <- summary(fit)
expect_true(inherits(s, "summary.rms"))
})
This is also equivalent to the following code (perhaps easier to understand):
env <- globalenv() # Grab the global environment
env$dd <- datadist(ds) # Assign the datadist to it
If you want to learn more about how environments work I can recommend Hadley's excellent Advanced R coverage of the topic. I found this explaining many of the issues that I was running into.
yes It is a scope problem as suggested by the error.
A possible work around is to define your ds
where you call test_dir
for example You create file, runtest.R
like this
library(rms)
set.seed(10)
ds <- data.frame(
ftime = rexp(200),
fstatus = sample(0:1,200,replace=TRUE),
x1 = runif(200),
x2 = runif(200),
x3 = factor(sample(LETTERS[1:3], size=200, replace=TRUE)))
ddist <- datadist(ds)
options(datadist="ddist")
library(testthat)
test_dir("inst/tests")
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With