R calls Python (basic usage of the recursive package)

1, Introduction to the basic usage of the retail package

The following content can be found in the document for retail:

1 Basic Introduction

CRAN included the reticulat package (version 1.6) on March 21, 2018, which includes a complete set of tools for collaborative operations between Python and R, and can be used in both R and Rstudio. Mainly including:

1) Support multiple ways to call Python in R. This includes R Markdown, loading Python scripts, importing Python modules, and interactively using Python in R sessions.

2) Implement conversions between R and Python objects (such as between R and Python data boxes, R matrices, and NumPy arrays).

3) Flexibly bind to different versions of Python, including virtual environments and Conda environments.

2. Operating instructions

1) Install and load the retail package .

#install reticulate package 
install.packages("reticulate")
#loading reticulate package 
library(reticulate)

2) Set up Python environment .

There are three methods for setting, see: Python Version Configuration.

Here, as I am using the Python environment of anaconda3, I am using use_Condaenv specifies the Python environment.

#py_available()#[1] FALSE  #check if your system has been installed before Python
use_condaenv("D:/Program Files (x86)/Anaconda3")
py_config()#installed python version environment view, displaying anaconda and numpy details of. 
py_available()#[1] TRUE   #check if your system has been installed before Python
py_module_available("pandas")#inspect"pandas"is it installed 

3) Import a Python module in R .

You can use import () to import any Python module and call it from R.

os <- import("os")
os$getcwd()
os$listdir()#you can use os in the package listdir () function to view all files in the working directory 
numpy <- import("numpy")
y <- array(1:4, c(2, 2))
y
x <- numpy$array(y)
x
numpy$transpose(x)#transpose an array 
numpy$linalg$eig(x)#finding eigenvalues and eigenvectors 

Note: You can use $ Operators access functions and other data in Python modules and classes (similar to how they interact with R lists, environments, or reference classes).

4) Interactive use of R and Python (Python REPL) .

By using repl_The Python () function interacts with R and Python. (Equivalent to creating an interactive Python console in R.).

  • Objects created in Python can be used in R, using py object to retrieve objects in Python, eg: py $train_Data.
  • Objects created in R can also be used in Python, using r object to retrieve objects in R, such as: r. mydata (specific examples can be found below)
repl_python()
#loading"panda"data set 
import pandas as pd
#load dataset 
train_data=pd.read_csv('iris.txt',header=None)
train_data.columns=['sepal_length','sepal_width','petal_length','petal_width','label']
#print(train_data.head(),train_data.shape,train_data.describe(include = 'all'))
train_data['label']=train_data.label.apply(lambda x: 1 if x=='Iris-setosa' else 0)
#display the number of rows and columns in the dataset 
train_data.shape
#randomly select the number of rows in the dataset 
train_data.sample(n = 10)
#back to R
exit
#utilize py object obtain python objects in 
summary(py$train_data)
#from Python obtain in R objects created in 
mydata = head(cars, n=15)
repl_python()
import pandas as pd
r.mydata.describe()
pd.isnull(r.mydata.speed)
exit

Note: You need to type "exit" to return to the R session .

5) Load Python script .

You can use the function: source_Python () retrieves any Python script, just like using an R script.

source_python("D:/python/R_python/test01.py") 
irisData <- read_Iris("iris.txt")
summary(irisData)

The test01.py script is:

import pandas as pd
def read_Iris(file):
train_data = pd.read_csv(file, header=None)
train_data.columns = ['sepal_length', 'sepal_width', 'petal_length', 'petal_width', 'label']
train_data['label'] = train_data.label.apply(lambda x: 1 if x == 'Iris-setosa' else 0)
return train_data

Example 2: Executing a Python file and calling variables in the Python file.

When adding (or changing) the following code to the Python script above:

def add(x, y):
return(x + y)
result = add(5,10)

Part R:

py_run_file("D:/python/R_python/test01.py") 
py$result  #[1] 15

Or when:

py_run_string("x=10;y=20")
py$x[1] #[1] 10
py$y[1] #[1] 20

6) Type conversion .

When Python is called, R data types are automatically converted to their equivalent Python types. When values are returned from Python to R, they are converted back to type R. If a Python object of a custom class is returned, the R reference of that object is returned. The type conversion is as follows:

The automatic conversion from R type to Python type works well in most cases, but occasionally it is necessary to provide Python's expected type more clearly in terms of R. For example, the Python API may require tuples instead of lists, in which case the tuple() function can be used to define.

2: Code implementation for calling Python with R

Test R calling Python to pass and return different data types (using the above content, some redundancy, only for recording).

Common parts of Python code:

import numpy as np

Common parts of R code:

#loading reticulate package 
library(reticulate)
#load Python script 
source_python("D:/python/R_python/first_Test.py") 

Note: The results of Python code in all of the following run results are listed later.

1. Pass and return numerical values

Python section:

#stay R middle, integer : integer ;  numeric : numerical type( double)
def add(x, y):
return x + y

Part R:

x=5.2
y=10.6
result1 <- add(x, y)
cat(x,'+',y,'=',result1,sep = '')#R language output :cat() print() paste () input :scan() readline()

Running results:

5.2+10.6=15.8

2. Pass and return a string

Python section:

def Hello(s):
print(s)
reStr=s+"nHello R!!"
return reStr

Part R:

s = 'Hello Python!!'
result2 <- Hello(s)
cat(result2)

Running results:

Hello Python!!
Hello R!!
Hello Python!!

3. Pass and return a one-dimensional list array (Python angle)

Python section:

def szTest(List):
print(List)
#print(type(List))#<class 'list'>

IntegerList = [1, 2, 3]
return IntegerList

Part R:

#passing a one-dimensional array( R of multi-element vector corresponding to Python of list)
sz=c(2.0,3.1,4.2,5.3,6.6)
#t=tuple("a", "b", "c")
result3 <- szTest(sz)
cat(result3)

Running results:

1 2 3
[2.0, 3.1, 4.2, 5.3, 6.6]

4. Pass and return a two-dimensional numpy array (Python angle)

Python section:

def szSecTest(npSzSec):
print(npSzSec)
#print(type(npSzSec))  #<class 'numpy.ndarray'>
IntegerList = [[1, 2, 3], [2, 3, 4]]
IntegerList =np.array(IntegerList)
return IntegerList

Part R:

#passing a two-dimensional array( R of Matrix/Array corresponding to Python of Numpy ndarray)
np_ma=matrix(c(1.1,2.2,3.3,4.4), nrow = 2, ncol = 2)
result4<- szSecTest(np_ma)
cat(result4)
dim(result4)

Running results:

1 2 2 3 3 4
[1] 2 3
[[1.1 3.3]
[2.2 4.4]]

5. Pass the list of R to Python and return it

Python section:

def list_Tuple(tuple_in):
#print(type(tuple_in))#<class 'list'>
print(tuple_in)
tuple_in[0] += 2
tuple_in[1] += 2
tuple_in[2] += ' add'
#print(type(tuple_in[3]))  # <class 'list'>
for i in range(len(tuple_in[3])):
  tuple_in[3][i]+=2
#print(type(tuple_in[4]))  # <class 'numpy.ndarray'>
row_= tuple_in[4].shape[0]
col_= tuple_in[4].shape[1]
x4=np.zeros((row_,col_))
for i in range(row_):
  for j in range(col_):
      x4[i][j]=tuple_in[4][i][j] +2
      #tuple_in[4][i][j] +=2 #error reporting :Error in py_call_impl(callable, dots$args, dots$keywords) : ValueError: assignment destination is read-only
#apply .pop () delete the last element 
tuple_in.pop()
tuple_in.append(x4)
return tuple_in

Part R:

#transmit list(R of List of multiple types corresponding to Python of Tuple but during testing, it was found that Python accepted as list type), it feels like it can be transmitted as a structure 
list_in=list(1L,2.0,'string',c(2.0,3.1,4.2,5.3,6.6),matrix(c(1.1,2.2,3.3,4.4,5.5,6.6), nrow = 2, ncol = 3))
result5<- list_Tuple(list_in)
result5

Running results:

[[1]]
[1] 3
[[2]]
[1] 4
[[3]]
[1] "string add"
[[4]]
[1] 4.0 5.1 6.2 7.3 8.6
[[5]]
[,1] [,2] [,3]
[1,]  3.1  5.3  7.5
[2,]  4.2  6.4  8.6
[1, 2.0, 'string', [2.0, 3.1, 4.2, 5.3, 6.6], array([[1.1, 3.3, 5.5],
 [2.2, 4.4, 6.6]])]

You can also use Python and R interactively to implement the above part, so we won't be recording it here.

The article referred to in this article:

Hand in hand | Wow! You can also run Python with R now.

Retail: R interface to Python.

R and Python, which are constantly being edited and messy.

Related articles