Tuesday, May 28, 2013

Using R to communicate via a socket connection

Occasionally, the need arises to communicate with R via another process. There are packages available to facilitate this communication, but for simple problems, a socket connection may be the answer. Nearly all software languages have a socket communication package, so this is very simple to implement.

First, start off with your R "server". In this case, I'm accepting text as input and upper casing it as a trivial example.


Then, use the client script to connect to the server and upper case some text. Here's an example in R...


Here's an example of the client in python. This will enable communication and data transfer between python and R.


To pull it all together, on the same machine, start up two command prompts. In the first one, start the R server via "Rscript server.R". Then in the other window, run the client script via "python client.py" or "Rscript client.R". In the client window, you should see a prompt to enter some text. Do so, and be amazed as you see your text returned from R in upper case.

Obviously, this can be reversed, with python or some other process being used as a "server" and R as the "client".

All of the code is included in a github repo

Shout out to my colleague JoeO for an early incarnation and an early use case for this process.

Follow me on twitter

2 comments:

  1. Thanks! Your post was very helpful.

    ReplyDelete
  2. Sir am using R studio , i am getting live data feeds from localhost and port , i want to connect it and have to plot live that data in R , am new to R, can u please help me how to do this.

    ReplyDelete

Note: Only a member of this blog may post a comment.