Home > Software design >  error in for-loops: could not find function "check_reserved"
error in for-loops: could not find function "check_reserved"

Time:10-23

When using R studio I get an error trying to use for-loops

for(i in 1:4){print(i)} Error in check_reserved(for_var_name) : could not find function "check_reserved"

Anyone any clue how to solve this? I've updated R, RStudio and restarted the session as well

session info:

R version 4.1.1 (2021-08-10) Platform: x86_64-apple-darwin17.0
(64-bit) Running under: macOS Big Sur 10.16

Matrix products: default

LAPACK:
/Library/Frameworks/R.framework/Versions/4.1/Resources/lib/libRlapack.dylib

attached base packages: [1] stats graphics grDevices utils datasets
methods base

loaded via a namespace (and not attached): [1] compiler_4.1.1
tools_4.1.1

Thanks!

CodePudding user response:

The error is because of a previous use of magic::magic_for which was somehow being brought back into the environment. The apparent intent of the function (no changes since 2016) is to allow a for loop to store the results of a modified function, something like:

library(magicfor)  # Load library
magic_for(print)   # Call magic_for()

for (i in 1:3) {
  squared <- i ^ 2
  print(squared)
}
#> The loop is magicalized with print().
#> [1] 1
#> [1] 4
#> [1] 9

magic_result_as_vector()  # Get the result
#> [1] 1 4 9

It appears that the "magicalization" of the print function was preserved (perhaps in .Rdata), but on a session restart, the magicfor package was not available (or just not loaded). I'd think that if the magicfor package is truly required for a workflow, then (1) make sure it's loaded, and (2) submit a bug to the author so that it better accommodates this scenario.

Lacking that, my suggestion for now:

  • do not load .Rdata files ("saved session" or similar); many feel it is far better to have a reproducible workflow and regenerate the intermediate/final structures you need vice loading them; the exception to this suggestion would be for long-running processes, but even then I think the better case is to explicitly save/cache just those values, not the entire session;
  • similarly, check .Rprofile and other R startup files to remove any mention of magicfor;
  • perhaps nuclear, but a community thread mentioned uninstalling the magicfor package; it's unclear if that was part of the resolution or not, though it seems unlikely if the underlying cause was a stale reference in an .Rdata file.
  • Related