Using R to communicate via a socket connection

[This article was first published on Stats and things, and kindly contributed to R-bloggers]. (You can report issue about the content on this page here)
Want to share your content on R-bloggers? click here if you have a blog, or here if you don't.

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 about learning R and many other topics. Click here if you're looking to post or find an R/data-science job.
Want to share your content on R-bloggers? click here if you have a blog, or here if you don't.

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)