“import as” in R

前端 未结 5 886
清歌不尽
清歌不尽 2020-11-27 17:46

Is there a way to import a package with another name in R, the way you might with import as in Python, e.g. import numpy as np? I\'ve been starting

5条回答
  •  一整个雨季
    2020-11-27 18:23

    Here's a solution that should only be used for interactive mode. You modify :: so that it can accept character package names, then write a function to register the aliases.

    `::` <- function(pkg, name) {
        sym <- as.character(substitute(pkg))
        pkg <- tryCatch(get(sym, envir=.GlobalEnv), error=function(e) sym)
        name <- as.character(substitute(name))
        getExportedValue(pkg, name)
    }
    
    pkg.alias <- function(alias, package) {
        assign(alias, package, .GlobalEnv)
        lockBinding(alias, .GlobalEnv)
    }
    
    pkg.alias('r', 'reshape2')
    r::dcast
    

    But instead of using aliases, you could also redefine :: to find the package that matches your abbreviation:

    `::` <- function(pkg, name)  {
        pkg <- as.character(substitute(pkg))
        pkg <- installed.packages()[grepl(paste0('^', pkg), installed.packages())]
        name <- as.character(substitute(name))
        getExportedValue(pkg, name)
    }
    
    ggp::ggplot
    

提交回复
热议问题