How to setup environment variable R_user to use rpy2 in python

前端 未结 6 1178
暗喜
暗喜 2020-11-28 08:43

I \'m unable to run rpy2 in python.

with this code

 import rpy2.robjects as robjects

Here\'s the full exceptions:


R

6条回答
  •  萌比男神i
    2020-11-28 09:22

    Combining answers from @laven_qa and @user3758274, here is what worked for me :

    # installing steps after downloading .whl from http://www.lfd.uci.edu/~gohlke/pythonlibs/#rpy2
    import pip
    pip.main(["install", "C:/Users/YOUR_USERNAME/Downloads/rpy2-2.8.6-cp36-cp36m-win_amd64.whl"]) # Path to the file that was downloaded from the website above
    
    # setting temporary PATH variables
    import os
    os.environ['R_HOME'] = 'C:\Program Files\Microsoft\R Open\R-3.4.0' #path to your R installation
    os.environ['R_USER'] = 'C:\ProgramData\Anaconda3\Lib\site-packages\rpy2' #path depends on where you installed Python. Mine is the Anaconda distribution
    
    # importing rpy2
    import rpy2.robjects as robjects
    
    # test : evaluating R code
    robjects.r('''
            # create a function `f`
            f <- function(r, verbose=FALSE) {
                if (verbose) {
                    cat("I am calling f().\n")
                }
                2 * pi * r
            }
            # call the function `f` with argument value 3
            f(3)
            ''')
    
    # returns : 
    > R object with classes: ('numeric',) mapped to:
    > 
    > [18.849556]
    

提交回复
热议问题