CoCalc Public Filespython3.RmdOpen in with one click!
Author: Harald Schilly
Views : 158
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.312,1.1])

Plotting

import numpy as np
import matplotlib.pyplot as plt
xx = np.linspace(0, 10, 100)
yy = np.sin(2 * 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)