R and Python Can Communicate

May 11, 2020   

Imagine you are sitting at your desk working through R studio and your mind begins wandering away. You start to think about what life would be like out of school, and begin to fantasize over your hopes and dreams. The nerd in me, however, begins to think about how R and Python can communicate with each other and how I could make that work.

Well, I am in luck because if you go online and listen to your professor who knows a lot (at least mine does), you’ll come to realize that this isn’t a very difficult task. To start, the ‘reticulate’ package must be installed in R, and that is what gets the two languages to understand eachother. It’s kind of like google translate…well not really, but you’ll get the point in a bit.

So after loading in the package, I think about what to say as a test run. Rather than keep it boring and lame, I try to crack a joke. Again, I am inserting this into an R chunk so nothing too crazy is happening yet, give me a break.

library(reticulate)
joke <- "My wife told me to stop acting like a flamingo."

Wait for it…

punchline= "I had to put my foot down."
print(r.joke,punchline)
## My wife told me to stop acting like a flamingo. I had to put my foot down.

And the audience goes…

via GIPHY

And then you realize another way that can execute this same joke is to use Python-defined functions in R code chunks.

cat(c(joke,py$punchline))
## My wife told me to stop acting like a flamingo. I had to put my foot down.

And this time the audience goes…

via GIPHY

And that, my friends, is how R and Python can communicate between languages.



comments powered by Disqus