Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

"import as" in R

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 to use package::function lately to avoid conflicts between, say, Hmisc::summarize and plyr::summarize.

I'd like to be able to instead write h::summarize and p::summarize, respectively. Is this possible in R?

like image 961
shadowtalker Avatar asked Jun 24 '14 15:06

shadowtalker


1 Answers

This is not quite what you want because it involves changing from :: notation to $ notation, but if you load a package namespace (without attaching it), you can then refer to it by its environment name:

h <- loadNamespace('Hmisc') p <- loadNamespace('plyr')  > summarize(iris$Sepal.Length, iris$Species, FUN=mean) Error: could not find function "summarize"  > Hmisc::summarize(iris$Sepal.Length, iris$Species, FUN=mean)   iris$Species iris$Sepal.Length 1       setosa             5.006 2   versicolor             5.936 3    virginica             6.588  > h$summarize(iris$Sepal.Length, iris$Species, FUN=mean)   iris$Species iris$Sepal.Length 1       setosa             5.006 2   versicolor             5.936 3    virginica             6.588  > summarise(iris, x = mean(Sepal.Length)) Error: could not find function "summarise"  > plyr::summarise(iris, x = mean(Sepal.Length))          x 1 5.843333  > p$summarise(iris, x = mean(Sepal.Length))          x 1 5.843333 

Note, however, that you do lose access to documentation files using the standard ? notation (e.g., ? p$summarise does not work). So, it will serve you well as shorthand, but may not be great for interactive use since you'll still have to resort to ? plyr::summarise for that.

Note also that you do not have access to the data objects stored in the package using this approach.

like image 108
Thomas Avatar answered Sep 25 '22 02:09

Thomas