SoFunction
Updated on 2024-11-14

Sample code for calling R in python3

Due to work needs, in doing the optimal split box, always write out the efficient code, so I found the R language in the optimal split box package, this time taking into account the call in python R language, the perfect combination. In the domestic Chinese site searched half a day, build the environment has been the emergence of " R_user not defined "this error, simply annoying, and finally on the site to find a solution.

My environment is: win7 ;

Use anaconda3 ;

(i) First you need an anaconda package;

Not much more to say on this one.

(ii) You need to have an R program.

I use the Microsoft development of this. Of course you use the R language software from the R official website, or you use RStudio is not a big problem.

/download

Setting environment variables to complete R with

1. Add the R directory to the path environment variable later.

path:D:\R\microsoft-r-open-3.4.2\bin\x64;

2. Add to the path environment variable

path:D:\R\microsoft-r-open-3.4.2\bin\x64\;

(c) Download rpy2 based on the experience of a small group of friends

Going to go unofficial and download a whl file.

/~gohlke/pythonlibs/#rpy2

Please recognize the python version and the 64-bit download, after downloading, install , put it under D:\Anaconda3\Anaconda3\Lib\site-packages, anyway, under your anaconda's site-packages.

command line in cmd, and then go to the path you just took.

C:\Users\Administrator>D:

D:\>cd D:\Anaconda3\Anaconda3\Lib\site-packa

D:\Anaconda3\Anaconda3\Lib\site-packages>pip install rpy2-2.8.6-cp36-cp36m-win_amd64.whl

At the end it will say successful and you are successful;

(iv) Configure the environment to test whether the code can run with R

Open up your python and bang on this code as you see fit and try it out.

In [1]: import os

In [2]: ['R_HOME'] = 'D:\R\microsoft-r-open-3.4.2'

In [3]: ['R_USER'] = 'D:\Anaconda3\Anaconda3\Lib\site-packages\rpy2'

In [4]: import  as robjects

In [5]: ('''
  ...:     # 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)
  ...:     ''')
Out[5]: 
R object with classes: ('numeric',) mapped to:
<FloatVector - Python:0x000000000B06FD88 / R:0x000000000EFE65B8>
[18.849556]

(v) Calling R's package

We usually use python to call R, and we usually have to use a special package that's not in python or something like that. So now I'm going to call the smbinning package, which is a package that enables optimal segmentation of data when it's split into boxes.

In [6]: from  import importr
In [7]: smbinning = importr('smbinning')

This is the entire content of this article.