AUser240
AUser240

Reputation: 15

Alternative to import() package in R?

I'm using Rpy2 within python to call R but for some reason I am not able to load a a specific package, 'rmgarch'. I have installed it separately in R and it works when I import it in RStudio, but for whatever reason, it just doesn't wanna work in rpy2, even though rpy2 is perfectly happy importing other packages such as 'rugarch', 'Matrix', 'zoo', etc. They are all installed in the same library which is even more confusing for me. My question is, do you know an alternative way of calling/importing the package while coding in R? Note that I can import any other package. I tried using devtools because that's the only similar thing I can think of, but it doesn't exist in that universe. I am using R 4.0.3. Python version 3.7.6. An example of the use in Jupyter is:

import rpy2
import rpy2.robjects as robjects
from rpy2.robjects import pandas2ri
from rpy2.robjects.conversion import localconverter

utils.install_packages('rmgarch') #;utils.install_pa...rugarch,...
robjects.r('''
        library('rugarch')
        library('quantmod')
        library('forecast')
        library('rmgarch')
        f <- function(u) {
            l<-u
        }
        ''')

The error output is:

RRuntimeError: Error in library("rmgarch") : there is no package called ‘rmgarch’

Upvotes: 0

Views: 412

Answers (2)

lgautier
lgautier

Reputation: 11545

The RRuntimeError forwards an error generated by R. It is says that there is no package X, the embedded R really thinks that there is no such package.

If observing a difference between say, an R embedded in RStudio and the one embedded in Python through, then it can be:

  • you have (at least) 2 R installed on your system and they each link to a different one
  • R is set up to look for installed packages in different places between the two (the environment variable R_LIBS can do that for example).

In RStudio:

installed.packages()["rmgarch", "LibPath"]

In Python/rpy2:

tuple(robjects.r('.libPaths()'))

If the path shown by R studio is not present in Python/rpy2, then Python/rpy2 will not be able to load an R package that RStudio can.

Upvotes: 1

Michael Dewar
Michael Dewar

Reputation: 3258

If you don't need the whole package, you can call individual functions using packagename::functionname(...).

Upvotes: 1

Related Questions