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)
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.
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.
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).
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 source
ing, but you should explicitly define a new function and specify all the arguments if you do this in a package.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With