Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Running python/bash code in Rstudio

I am using Rstudio for my day to day R stuff. Sometimes, I'd like to use some python/bash for the parts that R isn't super good at. Curiously enough I've noticed if I start an new RMarkdown document, that the following code works:

```{r engine='python'}
print "Hello" + "World"
import random
print random.random()
```

python in rstudio

Rstudio can run me some python. This is very useful, but preferably I would be able to run this not just via the markdown feature but through a console as well. In the release notes it is suggested that there is support for syntax highlighting.

I wonder, is there any method to connect a new console to Rstudio such that we could also do some python/bash from the IDE? It certainly seems like Rstudio has a notion of how to connect to python. The end goal would be to create .Rmd documents and be able to edit/interact with them that have the following structure:

# Use Case 

Connect to an api that is supported in python

```{r engine='python', highlight=TRUE}
data = foobar_api.get(1000)
file_loc = open("~/data/filename.csv", "w")
file_loc(data) 
file_loc.close()
```

Then analyse with R again. 

```{r}
df <- read.csv("~/data/filename.csv")
summary(df)
```
like image 497
cantdutchthis Avatar asked Dec 14 '15 09:12

cantdutchthis


People also ask

Can you run a Python script in RStudio?

Run Python Scripts in the RStudio IDE The RStudio IDE(opens in a new tab) is a free and open-source IDE for Python, as well as R. You can write scripts, import modules, and interactively use Python within the RStudio IDE. To get started writing Python in the RStudio IDE, go to File, New File, then Python Script.

How do I run Python code in R Markdown?

To add a Python code chunk to an R Markdown document, you can use the chunk header ```{python} , e.g., ```{python} print("Hello Python!") ```

Can Python interact with R?

Using R and Python together at the same time is incredibly easy if you already have your R scripts prepared. Calling them from Python boils down to a single line of code.


2 Answers

First you need to set the knitr options.

```{r}
knitr::opts_chunk$set(engine.path = list(python = '/anaconda/bin/python'))
```

From that point on it just works.

```{python}
import this 
```
like image 73
cantdutchthis Avatar answered Sep 19 '22 12:09

cantdutchthis


If you use Architect or plain Eclipse with StatET, you can install the PyDev plug-ins and launch and interact with Python consoles as easily as you would do with your R Consoles (and, there is, of course, ample support for editing and processing .Rmd files)

like image 42
Tobias Verbeke Avatar answered Sep 18 '22 12:09

Tobias Verbeke