R calls Python

Source: Internet
Author: User

The previous article said that Python calls R using Rpy2, here's how R calls Python. R's strengths are statistical aspects, especially professional statistical analysis, statistical testing and graphing function is very powerful, but in terms of versatility, is far less than python, such as Python can do the web, can develop a GUI, can crawler, and even can develop games, these r is not completely not, But it's hard to match python in terms of ease of use. So if you can combine R with Python and take advantage of both, then there's no doubt we'll get a more powerful weapon. Fortunately, R provides us with such a tool, Rpython.

Rpython is an interface that connects R with Python. Its homepage address is in: http://rpython.r-forge.r-project.org/. According to its official website, Rpython is to be able to compensate for the shortcomings of R in some areas of commonality, using Python's rich library to compensate for these shortcomings and was born. As to how Rpython works, the official website has written it very clearly:

How does does Rpython work?

One of the most daunting tasks in building an interface between, languages are provide mechanisms for exchanging differe NT data structures between them. Rpython uses JSON:

    1. R/python objects is dumped into JSON strings using their respective parsers (Rjsonio and Simplejson) respectively.
    2. These strings is passed between the languages using their string exchange mechanisms.
    3. JSON strings is finally reconstructed into language objects on the other side.

This simple mechanism allow R and Python exchange relatively complex data structures with ease.

The trouble with connecting R to Python is that the different data types of the two languages and the delivery of objects. The workaround used by Rpython is to use JSON as the intermediate object. The data and objects of Python and R are transformed into JSON strings first (python passes through the Simplejson library, r through the Rjsonio Library), and then into the data type of the corresponding language.

Here's a special mention of how Rpython is installed under Windows. If you are using a Linux or Mac system, then installing Rpython is a relatively simple thing, just use command install.packages ("Rpython"), but the pit daddy is, Rpython in Windows does not have a compiled package (formerly if I install.packages in Windows under the installation failed, go directly to the Cran official website to find the corresponding compiled package, and then extracted to the library directory of R, you can use directly), so we have to build the installation The At first, I did not find the right way to install Rpython, and later found Rjython this package, the package on the Cran has been compiled, I successfully installed after the discovery can also be used. In addition, we usually refer to Python as the C implementation of Python, CPython, but there are other language implementations of Python, such as Jython is the Java implementation of Python, IronPython is python on the. NET and mono platforms. PyPy is a python written using pure Pyhton. Interested in this can be self-access information. Because it is not rpython, so I can only use Jython, the use of Jython pros and cons, and of course, it is possible to seamlessly call Java a lot of class library, the disadvantage is jython third-party library compared to CPython less poor, many libraries can not be used, So it's also a matter of comparing the pain of an egg.

But today, I finally found a way to install Rpython under Windows on GitHub. Link here: Https://github.com/cjgb/rPython-win. The approximate installation steps are as follows:

1. Download the github zip file

2. After the download is complete, unzip the folder and rename it to Rpython

3. Install Devtools under R (a package management tool that can download R packages from GitHub), Install.packages ("Devtools")

4.library (Devtools)

5. Open the Configure.win file after decompression, probably the following looks like:

#!/bin/sh

Echo ' pkg_libs=-lc:/python27/libs -lpython27 ' > Src/makevars.win
Echo ' pkg_cflags=-i 'c:/python27/include' >> Src/makevars.win

The original default Python installation location is c:/python27, which needs to be changed to the actual location of Python installed on your own computer, so that the installation location of Python can be correctly found at compile time.

When done, execute the command: Install ("Yourpath/rpython"), and the quotation marks are the location where you unzipped the Rpython. At this point, Rpython was successfully installed. If the installation process error, such as my error, unable to download Rjsonio, please install the corresponding missing library.

After the installation is successful, let's take a look at how to use Rpython.

In fact, the use of Rpython is relatively simple, it provides a number of call interface functions. Look directly at the code example:

1 #R calls Python2 Library (Rpython)3Python.call ("Len", 1:10)#calling Functions4A <-0:35b <-1:46Python.exec("def connact (A, B): Return a+b")#Execute function7C <-Python.call ("connact", A, B)#calling Functions8Python.assign ("a","Hola" )9A.split <-Python.method.call ("a","Split"," ")#call the Split function to a, use space to split

First load Rpython this library.

Python.call ("Len", 1:3) means that the Len function that calls Python calculates the vector of 1:3, which is actually the calculation of Len ([+]), and the answer is, of course, 3. Python.exec () can execute a python code, here is the execution of a Python function, we define the addition of two variables, and then call this function by using calls, the function of two parameters is a, a, the result of the calculation is C. The calculation can get C (0,1,2,3,1,2,3,4) as a vector, in fact, we can find that the vector in R corresponds to the list in Python. Then use Python.assign () to assign the string "Hola" to the variable a, and then call the split method on a, split passed in the parameter is a space, that is, a by space split, the result is "Hola" "Hola" the two strings.

Other methods of use, you can refer to the Cran function help manual, or directly?? Rpython view the Help documentation.

Finally, see how to invoke execute a python file in R.

The file named python_demo.py is as follows:

#-*-coding:utf-8-*-ImportRequests" "simulate landing a website called Push cool" "s=requests.session ()#data is to be submitted and can be captured via Firefox's Httpfoxdata = {    'Email':'[email protected]',    'Password':'xxxxxxx',    'Authenticity_token':'anjyaqei/iqqiftlfu4md41p418qignozgijjmwkz9a=',    'Remember':'1'}url_login='Http://www.tuicool.com/login' #address to submit data forheaders = {'user-agent':'mozilla/5.0 (Windows NT 6.3; Win64; x64) applewebkit/537.36 (khtml, like Gecko) chrome/41.0.2272.118safari/537.36'}res=s.post (url_login,data,headers =headers) R=s.get (url_login) content=R.contentwith Open ('tuiku.html','W') as F:f.write (content)

The code above uses the requests library to impersonate a Web site and write the returned content to an HTML file.

This python file can be executed from R by using just a few lines of code.

# To invoke a python file using Rpython " f:/r_work/rpython/python_demo.py "  #  call python file

Run the above code in R, and after a few seconds, you will find that an HTML file has been added. What, isn't it cool?

With the Rpython, later, such as data capture and large-scale operation of the task can be handed to Python, get the data and then into R, and then use R's Professional statistical package for statistical analysis and mapping. A seamless combination of Python and R, so cool!

R calls Python

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.