Using R to communicate via a socket connection

May 28, 2013

(This article was first published on Stats and things, and kindly contributed to R-bloggers)

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” 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

To leave a comment for the author, please follow the link and comment on their blog: Stats and things. offers daily e-mail updates about R news and tutorials on topics such as: Data science, Big Data, R jobs, visualization (ggplot2, Boxplots, maps, animation), programming (RStudio, Sweave, LaTeX, SQL, Eclipse, git, hadoop, Web Scraping) statistics (regression, PCA, time series, trading) and more...

If you got this far, why not subscribe for updates from the site? Choose your flavor: e-mail, twitter, RSS, or facebook...

Comments are closed.


Never miss an update!
Subscribe to R-bloggers to receive
e-mails with the latest R posts.
(You will not see this message again.)

Click here to close (This popup will not appear again)