I am working with a segmented package and ran into a problem when calling davies.test() from inside a function.
Consider the following situation:
library(segmented) data = data.frame(x = 1:21, y = c(10:1, 0:10)) fit = lm(y ~ x, data = data) fit.seg = segmented(fit, seg.Z = ~ x) davies.test(fit.seg, seg.Z = ~ x, alternative = "greater")
This works great and indicates that segmented regression has two statistically different slopes.
Now, if I pack it all in a function like this:
testit <- function() { data = data.frame(x = 1:21, y = c(10:1, 0:10)) fit = lm(y ~ x, data) fit.seg = segmented(fit, seg.Z = ~ x) davies.test(fit.seg, seg.Z = ~ x, alternative = "greater")$p.value } testit()
Then it works fine ...
But if I remove fit from the global environment, this will not work.
> rm(fit) > testit() Error in eval(expr, envir, enclos) : object 'fit' not found
The problem is that davies.test trying to access the data encapsulated in fit : it doesn't seem to look for fit in the scope (in this case, testit ), but it passes directly to the global scope.
I am sure that the problem is due to some subtlety with the rules for defining R. If I find a quick fix that would prevent me from bothering the author of the package with this case, that would be great.
Thanks Andrew.