Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

r

In python I can load a specific function or functionality with:

from x import y as z

How can I replicate this in R?

For instance, I want to load just the count function from plyr, instead of loading the entire package with library(plyr)

like image 468
emehex Avatar asked May 19 '15 19:05

emehex


People also ask

What is from X import Y in Python?

from x import y will only import y from module x . This way, you won't have to use dot-notation. (Bonus: from x import * will refer to the module in the current namespace while also replacing any names that are the same) import x as y will import module x which can be called by referring to it as y.

What is the meaning of import* in python?

In Python, you use the import keyword to make code in one module available in another. Imports in Python are important for structuring your code effectively. Using imports properly will make you more productive, allowing you to reuse code while keeping your projects maintainable.

How do you use %paste in Python?

To copy text, just select it and hit Ctrl-C (Command-C on a Mac). If the highlight marking the selection disappears, that's normal and it means it's worked. To paste, use Ctrl-V (Command-V on a Mac).


1 Answers

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.

like image 145
Joshua Ulrich Avatar answered Sep 21 '22 13:09

Joshua Ulrich