Simply mix text and R-code

The data-frame mtcars has the following columns: mpg, cyl, disp, hp, drat, wt, qsec, vs, am, gear, carb.

Here are the first rows and columns:

##                 mpg cyl disp  hp drat    wt  qsec vs am
## Mazda RX4      21.0   6  160 110 3.90 2.620 16.46  0  1
## Mazda RX4 Wag  21.0   6  160 110 3.90 2.875 17.02  0  1
## Datsun 710     22.8   4  108  93 3.85 2.320 18.61  1  1
## Hornet 4 Drive 21.4   6  258 110 3.08 3.215 19.44  1  0

And here is a plot:

ggplot(mtcars, aes(x = wt, y = mpg, colour = cyl, size = hp)) + 
  geom_point() + 
  geom_smooth()
A plot generated by R on R-data.

A plot generated by R on R-data.

Run Python in R and use the R-objects

print("This is printed by Python.")
## 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:

mpg_py = r.df['mpg']
print(mpg_py[1:8])
## Mazda RX4 Wag        21.0
## Datsun 710           22.8
## Hornet 4 Drive       21.4
## Hornet Sportabout    18.7
## Valiant              18.1
## Duster 360           14.3
## Merc 240D            24.4
## Name: mpg, dtype: float64
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))
## The average of MPG is: 20.09

Use the Python objects in R

library(ggplot2)
library(tidyverse)
tbl <- tibble(mpg = py$mpg_py)

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