12

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)
```
cantdutchthis
  • 31,949
  • 17
  • 74
  • 114

3 Answers3

5

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 
```
cantdutchthis
  • 31,949
  • 17
  • 74
  • 114
2

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)

Tobias Verbeke
  • 422
  • 4
  • 7
1

This is an example of knitr at it's best, where it allows for multiple language engines. You might consider editing the file for just these cases in VIM, because you can do something fun that is close to what you are asking: select the text and then type:

:'<,'>!python

to execute in python and

:<','>!R --no-save

To execute in R. See the answers to this question for more details.

The above does not solve the use case completely, because the selected text is replaced by the output of the command (starting with the R version etc. in the case of a simple R command). It is possible however, to send the output to a different buffer (read: window) using this vimtip.

The VIM-mode in RStudio is nothing short of excelent (it even supports visual block mode). But it cannot emulate everything and :!python in RStudio will not work. I often have the document I'm working on open in both RStudio and VIM, and the above might be a reason for you to do the same for Rmd documents with mixed languages.

Community
  • 1
  • 1
FvD
  • 3,697
  • 1
  • 35
  • 53