---
title: "R and Python Living in Harmony"
author: "Philippe De Brouwer"
date: "22/03/2021"
output: html_document
---

```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = TRUE)
knitr::opts_chunk$set(warning = FALSE)
knitr::opts_chunk$set(message = FALSE)
if(!require(reticulate)) install.packages("reticulate")
library(reticulate)
library(ggplot2)
#scipy <- import("pandas")
#use_python("/usr/bin/python2.7")

## Define a data-frame
df <- mtcars
```

## Simply mix text and R-code

The data-frame `mtcars` has the following columns: `r colnames(mtcars)`

Here are the first lines:
```{r head, echo=F}
head(mtcars)
```

And here is a plot:
```{r gg, fig.cap="A plot generated by R on R-data."}
ggplot(mtcars, aes(x = wt, y = mpg, colour = cyl, size = hp)) + 
  geom_point() + 
  geom_smooth()
```


## Run Python in R and use the R-objects

```{python}
print("This is printed by Python.")
```

Note that we can access all R-variables in the object 'r'. The following code fragments uses the object `df` from R:
```{python sec}
mpg_py = r.df['mpg']
print(mpg_py)

def averageOfList(num):
    sumOfNumbers = 0
    for t in num:
        sumOfNumbers = sumOfNumbers + t

    avg = sumOfNumbers / len(num)
    avg = round(avg, 2)
    return avg

print("The average of MPG is:", averageOfList(mpg_py))
```

### Print something in Python
```{python}
mpg_py.plot.hist(grid=True, bins=20, rwidth=0.9,
                   color='#607c8e')
```

## Use the Python objects in R

```{r cars}
library(ggplot2)
library(tidyverse)
tbl <- tibble(mpg = py$mpg_py)

ggplot(tbl, aes(y = mpg)) + geom_boxplot(fill="khaki3")
```


