CoCalc Public Filespython3.RmdOpen with one click!
Author: Harald Schilly
Views : 225
License: Apache License 2.0

title: Python3 in RMarkdown on CoCalc

# set include=FALSE to hide the setup
library(reticulate)
use_python("/usr/bin/python3")
import sys
print(sys.executable)
print(sys.version)
import numpy as np
x = np.array([1,2,3,-1,2.3,12])

Plotting

import numpy as np
import matplotlib.pyplot as plt
xx = np.linspace(0, 10, 1000)
yy = np.sin(2 * np.exp(-xx))
plt.plot(xx, yy)
plt.show()

R still works, too

plotting same plot via R

plot(py$xx, py$yy, type = 'l', col = "blue", lwd=2)

Interactions between R and Python

This uses the reticulate R library:

Retrieve the value of x from the Python session again:

py$x
summary(py$x)

Assign to a variable in the Python session from R:

py$y = 1:5

See the value of y in the Python session:

print(y)

# colorFunc <- "heat.colors"
colorFunc <- "terrain.colors"
# colorFunc <- "topo.colors"
# colorFunc <- "cm.colors"
# colorFunc <- "rainbow"

Base R comes with many functions for generating colors. The code below demonstrates the r colorFunc function.

Blah blah!

r colorFunc

image(volcano, col = get(colorFunc)(5))