How can a non-imported method in a not-attached package be found by calls to functions not having it in their namespace?

后端 未结 1 1074
-上瘾入骨i
-上瘾入骨i 2020-11-30 05:54

An R namespace acts as the immediate environment for all functions in its associated package. In other words, when function bar() from package foo

相关标签:
1条回答
  • 2020-11-30 06:28

    I'm not sure if I correctly understand your question, but the main point is that group is character vector while data$group is factor.

    After attaching gmodels, the call for reorder(factor) calls gdata:::reorder.factor. so, reorder(factor(group)) calls it.

    In transform, the function is evaluated within the environment of the first argument, so in T2 <- transform(data, group = reorder(group,-num)), group is factor.

    UPDATED

    library attaches the import packages into loaded namespace.

    > loadedNamespaces()
     [1] "RCurl"     "base"      "datasets"  "devtools"  "grDevices" "graphics"  "methods"  
     [8] "stats"     "tools"     "utils"    
    > library(gmodels) # here, namespace:gdata is loaded
    > loadedNamespaces()
     [1] "MASS"      "RCurl"     "base"      "datasets"  "devtools"  "gdata"     "gmodels"  
     [8] "grDevices" "graphics"  "gtools"    "methods"   "stats"     "tools"     "utils"    
    

    Just in case, the reorder generic exists in namespace:stats:

    > r <- ls(.__S3MethodsTable__., envir = asNamespace("stats"))
    > r[grep("reorder", r)]
    [1] "reorder"            "reorder.default"    "reorder.dendrogram"
    

    And for more details

    The call of reorder will search the S3generics in two envs:

    see ?UseMethod

    first in the environment in which the generic function is called, and then in the registration data base for the environment in which the generic is defined (typically a namespace).

    then, loadNamespace registers the S3 functions to the namespace.

    So , in your case, library(gmodels) -> loadNamespace(gdata) -> registerS3Methods(gdata).

    After this, you can find it by:

    > methods(reorder)
    [1] reorder.default*    reorder.dendrogram* reorder.factor*    
    
       Non-visible functions are asterisked
    

    However, as the reorder.factor is not attached on your search path, you cannot access it directly:

    > reorder.factor
    Error: object 'reorder.factor' not found
    

    Probably this is whole scenario.

    0 讨论(0)
提交回复
热议问题