The R equivalent of Python `from x import y as z`

from plyr import count as count could look like this:

count <- function(x) {
    plyr::count(x)
}

Simplified:

count <- plyr::count

More complete:

if (requireNamespace("plyr")) 
    count <- plyr::count

EDIT:

I was inspired by @eipi10's comment. I was unaware of ::
Thanks @Joshua Ulrich for the suggestions!


I'd probably just do count <- plyr::count, so I wouldn't have to bother with ensuring I get the arguments correct.

And you might want to wrap that definition in an if statement, in case plyr isn't installed:

if (requireNamespace("plyr"))
    count <- plyr::count
else
    stop("plyr is not installed.")

Also you might be interested in the import and/or modules packages, which provide python-like import/module mechanisms for R.


Also heed the warning from the Adding new generics section of Writing R Extensions (original emphasis):

Earlier versions of this manual suggested assigning foo.default <- base::foo. This is not a good idea, as it captures the base function at the time of [package] installation and it might be changed as R is patched or updated.

So it would be okay to use the count <- plyr::count syntax if it's defined in a script you're sourceing, but you should explicitly define a new function and specify all the arguments if you do this in a package.

Tags:

R