R包migraR上传CRAN遇eval报错:避免attach后找不到对象‘x’
best_migramod Function Let’s break down your problem and fix that environment-related error—first, let’s get rid of the attach() approach entirely, since it’s unreliable (and frowned upon in CRAN package development for good reason: it pollutes the global environment and causes unpredictable behavior in function contexts).
Root Cause
The error happens because when fit_migramod calls eval(.self$expr, c(as.list(p), as.list(data))), the evaluation environment doesn’t properly prioritize the variables in your data1 object. When you remove the explicit colnames and attach, R can’t find x and y because they’re not in the scope where eval() is looking.
Solutions
1. Use Explicit Data Environment in eval()
Modify the eval() call inside your Migramodel class method to explicitly use the data’s environment. Replace your current eval line with something like this:
eval(.self$expr, envir = list2env(c(as.list(p), data), parent = parent.frame()))
This merges your parameters p with the data into a new environment, ensuring x and y are visible during evaluation. Alternatively, use with() to wrap the evaluation, which makes the data’s variables available directly:
with(data, eval(.self$expr, envir = as.list(p)))
2. Pass Data Explicitly Through Function Calls
Ensure best_migramod explicitly passes the data object to fit_migramod, and that fit_migramod passes it along to the Migramodel methods. Avoid relying on global variables or attach()—instead, make data a required parameter for these functions if it isn’t already. For example:
best_migramod <- function(data, ...) { # Explicitly pass data to fit_migramod fit_migramod(data = data, ...) }
3. Use rlang for Safer Evaluation (Optional but Recommended)
If you’re open to adding a dependency on the rlang package (which is CRAN-friendly), use rlang::eval_tidy() instead of base eval(). It handles environments more intuitively and avoids common scoping pitfalls:
rlang::eval_tidy(.self$expr, data = c(as.list(p), data))
4. Debug to Confirm Scope
If you’re still unsure where the variable is getting lost, insert a browser() call right before the failing eval() line. When the error triggers, you can run ls() to see what variables are in the current environment, or find("x") to check where R is searching for the object. This will help you pinpoint exactly where the scope breaks.
Critical Note for CRAN Submission
Never use attach() or detach() in package code—CRAN reviewers will likely flag this, and it’s bad practice because it can interfere with the user’s workspace. All data references should be explicit and contained within the function’s scope.
内容的提问来源于stack exchange,提问作者El Flaco

