Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can i connect pyRserve with Python

i need to connect pyRserve in iPython, but there is an error when i try to connect it. This is the error.

conn = pyRserve.connect()

And this is what i get:

RConnectionRefused: Connection denied, server not reachable or not accepting connections.

In the pyrserve manual are and advice to correct this, but i don't understand what i need to do. This is the advice (Note)

Note When a remote connection to Rserve should be opened, and pyRserve cannot connect to it, most likely Rserve only listens to it’s own internal network connection. To force Rserve accepting connections from other machines create a file called /etc/Rserv.conf and add at least the following line: remote enable Then restart Rserve.

So, i need to know how to implement the note and connect the Rserve in python

Thanks everyone

like image 310
Daniel Romero Avatar asked May 12 '16 19:05

Daniel Romero


Video Answer


2 Answers

In R (using 3.3.2)

install.packages(‘Rserve’)
library(Rserve)
Rserve()    # the actual server you will be calling from python

After running Rserve() you should see the following which indicates R server is running: Starting Rserve... "C:\Users\bkeith\Desktop\R-33~1.2\library\Rserve\libs\x64\Rserve.exe"


In Python

import pyReserve
conn = pyRserve.connect()  # the connection to R

print conn
>> <Handle to Rserve on localhost:####>

Once this prints, you’re good to start using the library.


Don’t forget to close your connection, to check it you can use conn.isClosed:

conn.shutdown()

Here’s some examples from the library:

Ex.1 – basic syntax

conn.eval(‘2+4’) #basic eval
>> 6.0

Ex.2 – list from python to R

a = [1,2,3,4]   #python list
conn.r.a = a    #the R variable is named a as well 
print conn.r.a 
>>[1,2,3,4]     #the R list is now in python as well

Ex.3 – Function in R

conn.voidEval(‘two <- function(x){ x * 2}’) #declare the function
conn.eval(‘two(9)’)   #use the function
>> 18.0
like image 112
BarclayK Avatar answered Nov 06 '22 18:11

BarclayK


I had exactly the same issue with you before and was able to solve it by installing Rserve, make sure you download the file from their website and run the codes below:

R CMD INSTALL [Rserve_1.8-0.tar.gz] #put in the file name

And then when running this in the terminal:

R CMD Rserve

There should be messages indicating that r is in daemon mode, and then running conn = pyRserve.connect() should be no problem from there.

like image 44
Carl PCH Avatar answered Nov 06 '22 19:11

Carl PCH