“import as” in R

前端 未结 5 897
清歌不尽
清歌不尽 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:29

    Rather than aliasing the package, why not just alias the function?

    hsumm <- Hmisc::summarize
    dsumm <- dplyr::summarize
    psumm <- plyr::summarize
    

    I was starting down an eval(parse()) path, but I ran into trouble and need to get back to work. @Thomas's answer seems to get a similar result in a much smoother way, but here's the non-working draft.

    package_alias <- function(package, alias, infix = "..") {
        funs <- ls(paste0("package:", package))
        for (i in seq_along(funs)) {
            assign(paste0(alias, infix, funs[i]),
            value = eval(parse(text = funs[i])), envir = .GlobalEnv)
        }
    }
    

    With the idea that you could do something like

    package_alias("plyr", "p")
    

    to create p..ddply, etc.

提交回复
热议问题