Home > Article > Backend Development > How to call R in python
Python and R are the two mainstream languages for data analysis today.
Python is a general programming language, scientific computing and data analysis are important components, but not all; while R is more focused on statistical analysis. After all, R is statistics. It was invented by scientists and was born for statistics. (Recommended learning: Python video tutorial)
The advantage of python is its versatility. Python is used in almost all fields, while R is very professional in statistics and related fields. Both have their own advantages. So can these two good things be combined?
The answer is yes. To realize this function, a corresponding calling interface must generally be provided. The third-party library rpy2 provides an interface for python to call R. This article mainly introduces the simple use of rpy2.
Commonly used commands:
1. import rpy2.robjects as robjects This command is to import r objects
2. robjects.r ("r_script") can execute R code, such as pi = robjects.r('pi') to get the PI (pi) in R. The returned variable pi is a vector, or it can be understood as a list in python. Through pi [0] can get the value of pi.
3. robjects.r.source(“file.r”) can execute r script files. The example is as follows:
robjects.r.source('plot_demo.r')
plot_demo.r The content is as follows:
# R 语言测试脚本 x <- c(1,2,3,4) y <- x*x jpeg(file="plot.jpg") # 保存图像 plt <- plot(x,y) # 画散点图 dev.off() # 关闭设备
For more Python related technical articles, please visit the Python Tutorial column to learn!
The above is the detailed content of How to call R in python. For more information, please follow other related articles on the PHP Chinese website!