问题
I am trying to build a function which wraps around the ordiR2step()
function from the vegan
package. This function is based on the step()
function.
This is the code to that works perfectly well outside of a function:
install.packages("vegan")
require(vegan)
data(mite)
data(mite.env) #explanatory variables
mite.hel = decostand(mite, "hel") #response variable
mod0 <- rda(mite.hel ~ 1, mite.env) # Model with intercept only
mod1 <- rda(mite.hel ~ ., mite.env) # Model with all explanatory variables
step.res <- ordiR2step(mod0, scope = formula(mod1), direction="forward")
step.res$anova
However, if I try and wrap this into a function:
forward <- function(X, Y) {
intercept <- rda(X ~ 1, data = Y) # Model with intercept only
model <- rda(X ~ ., data = Y) # Model with all explanatory variables
# this is where debugging is stuck
forStep <- ordiR2step(object=intercept, scope = formula(model),
direction = "forward", trace = FALSE)
list(forStep$anova)
}
forward(mite.hel, mite)
I get the following error: Error in eval(expr, envir, enclos) : object 'X' not found
I know some problems can arise when trying to wrap these types of functions, and these issues have been been discussed many times on stackoverflow and other places, such as here, here and here. However, none of these solution seem to have worked properly.
From my understanding of this behaviour, the step()
function, and by extension the ordiR2step()
, cannot read from the environment defined within the function, but only from the work space environment, because if I define X
before calling the function, everything works well. However this defeats the purpose, so I tried some proposed solutions such as:
forward2 <- function(X, Y) {
intercept <- do.call("rda",list(X ~ 1, data = Y))
model <- do.call("rda", list(X ~ ., data = Y))
forStep <- ordiR2step(object=intercept, scope = formula(model),
direction = "forward", trace = FALSE)
list(forStep$anova)
}
forward2(mite.hel, mite.env)
Same error... No dice... Any suggestions? Thanks for your time!
来源:https://stackoverflow.com/questions/23670014/user-defined-function-based-on-step-gives-error-in-evalexpr-envir-enclos