Run Python in RMarkdown
Knitr setting for rmarkdown export
- library(reticulate)
- py_config: see current python version
- use_virtualenv(“py39bert”)
- Enable knit_engine to use python for rmarkdown export purpose
- knitr::knit_engines$set(python = reticulate::eng_python)
library(reticulate)
py_home <- py_config()
use_virtualenv(py_home$virtualenv)
knitr::knit_engines$set(python = reticulate::eng_python)
Install Python 3.9 on Ubuntu
Check Ubuntu version
lsb_release -a
Update packages
sudo apt update sudo apt -y upgrade
Install python 3.9
sudo apt install python3.9 python3 -V python3.9 -V
Install pip
python3.9 -m pip install --upgrade pip
Install virtualenv
pip3 install virtualenv which virtualenv
Create a virtualenv using Python 3.9 named as py39bert
which python3.9 virtualenv -p /usr/bin/python3.9 py39bert
Activate the virtualenv
source ~/py39bert/bin/activate
Install ipython and jupyter notebook within virtualenv
pip3 install ipython pip3 install jupyter notebook jupyter notebook to start jupyter notebook
Install python packages within the virtualenv
pip3 install numpy
Install Python packages within R
- Run python module within R
library(reticulate)
py_home <- py_config()
use_virtualenv(py_home$virtualenv)
## virtualenv_install(py_home$virtualenv, "feather")
os <- import("os")
os$environ['HOME']
[1] “/home/ghowoo”
[1] “flowchart.Rmd” “data_manipulation.Rmd”
Install Python packages within Python
Save Data in R
library(feather)
library(data.table)
dt <- data.table(v1=1:6, v2=rep("A", 6))
write_feather(dt, "dt.feather")
list.files(pattern = "*.feather")
[1] “dt.feather”
Read feather in Python
import os
#print(os.getcwd())
path = os.getcwd()
os.chdir(path)
print(os.listdir()[0:4])
#print(os.getcwd())
[‘flowchart.Rmd’, ‘data_manipulation.Rmd’, ‘discretization.Rmd’, ‘graph.Rmd’]
import pandas as pd
# import feather
path = "dt.feather"
df = pd.read_feather(path)
from tabulate import tabulate
print(tabulate(df, tablefmt='html'))
0 | 1 | A |
1 | 2 | A |
2 | 3 | A |
3 | 4 | A |
4 | 5 | A |
5 | 6 | A |
reticulate
- virtualenv_list() lists virtual environment
- use_virtualenv(“virtual-environment-name”): initiate python from virtual-environment, required = TRUE check if there is the version, otherwise may search for other versions
- use_python(“python path”): initiated python from path
- py_config() to see version
## library(reticulate)
## Sys.setenv(RETICULATE_PYTHON = "/home/gongw/.virtualenvs/pybert/bin/python3.9")
## Sys.setenv(LD_LIBRARY_PATH = paste(
## "/home/gongw/.virtualenvs/pybert/lib"
## , Sys.getenv("LD_LIBRARY_PATH")
## , sep = ":"))
## use_python("/home/gongw/.virtualenvs/pybert/bin/python3.9")
library(reticulate)
## use_python("/home/gongw/.virtualenvs/py39bert/bin/python3.9")
## use_python("/usr/bin/python3")
use_virtualenv("py39bert")
py_config()
py_discover_config()
## py_install()
## reticulate::py_config()
virtualenv_list()
## reticulate::use_python("/usr/bin/python3")
## use_virtualenv("py39bert", required = TRUE)
## py_available()
## reticulate::use_python("~/venv/pybert/bin/python3")
os <- import("os")
os$listdir(".")
sys <- import("sys")
sys$version
## py_install("pandas")
#py_install("pandas", method = "auto", conda = "auto")
python matplotlib
3.9.12 (main, Mar 24 2022, 16:20:11) [GCC 9.4.0]
Python print table
hello, python world!
import numpy as np
# a = np.arange(5)
table = [['one','two','three'],['four','five','six'],['seven','eight','nine']]
from tabulate import tabulate
print(tabulate(table, tablefmt = 'html', headers = ["Column I", "Column II", "Column III"]))
Column I | Column II | Column III |
---|---|---|
one | two | three |
four | five | six |
seven | eight | nine |
Save Python plot
To show plot in rmarkdown
![matplot](pythton_pyplot.png)
import matplotlib.pyplot as plt
fig, ax = plt.subplots( nrows=1, ncols=1 )
ax.plot([0,1,2], [10,20,3])
#ax.show()
# plt.plot([1,2,3],[3,4,5])
# plt.show()
fig.savefig("pythton_pyplot.png")
plt.close(fig)
Python Version
sys.version_info(major=3, minor=9, micro=12, releaselevel=‘final’, serial=0)
R sessionInfo()
R version 4.1.2 (2021-11-01) Platform: x86_64-pc-linux-gnu (64-bit) Running under: Ubuntu 20.04.3 LTS
Matrix products: default BLAS: /usr/lib/x86_64-linux-gnu/blas/libblas.so.3.9.0 LAPACK: /usr/lib/x86_64-linux-gnu/lapack/liblapack.so.3.9.0
locale: [1] LC_CTYPE=C.UTF-8 LC_NUMERIC=C LC_TIME=C.UTF-8
[4] LC_COLLATE=C.UTF-8 LC_MONETARY=C.UTF-8 LC_MESSAGES=C.UTF-8
[7] LC_PAPER=C.UTF-8 LC_NAME=C LC_ADDRESS=C
[10] LC_TELEPHONE=C LC_MEASUREMENT=C.UTF-8 LC_IDENTIFICATION=C
attached base packages: [1] stats graphics grDevices utils datasets methods base
other attached packages: [1] feather_0.3.5 reticulate_1.24 Wu_0.0.0.9000
[4] flexdashboard_0.5.2 lme4_1.1-27.1 Matrix_1.4-0
[7] mgcv_1.8-38 nlme_3.1-152 png_0.1-7
[10] scales_1.1.1 nnet_7.3-16 labelled_2.8.0
[13] kableExtra_1.3.4 plotly_4.9.4.1 gridExtra_2.3
[16] ggplot2_3.3.5 DT_0.18 tableone_0.13.0
[19] magrittr_2.0.1 lubridate_1.7.10 dplyr_1.0.7
[22] plyr_1.8.6 data.table_1.14.0 rmdformats_1.0.2
[25] knitr_1.36
loaded via a namespace (and not attached): [1] httr_1.4.2 sass_0.4.0 tidyr_1.1.3 jsonlite_1.7.2
[5] viridisLite_0.4.0 splines_4.1.2 here_1.0.1 bslib_0.2.5.1
[9] highr_0.9 yaml_2.2.1 pillar_1.6.4 lattice_0.20-45
[13] glue_1.5.1 digest_0.6.29 rvest_1.0.0 minqa_1.2.4
[17] colorspace_2.0-2 htmltools_0.5.2 survey_4.0 pkgconfig_2.0.3
[21] haven_2.4.1 bookdown_0.22 purrr_0.3.4 webshot_0.5.2
[25] svglite_2.0.0 tibble_3.1.6 generics_0.1.0 ellipsis_0.3.2
[29] withr_2.4.3 lazyeval_0.2.2 survival_3.2-13 crayon_1.4.2
[33] evaluate_0.14 fansi_0.5.0 MASS_7.3-54 forcats_0.5.1
[37] xml2_1.3.3 tools_4.1.2 hms_1.1.0 mitools_2.4
[41] lifecycle_1.0.1 stringr_1.4.0 munsell_0.5.0 compiler_4.1.2
[45] jquerylib_0.1.4 systemfonts_1.0.2 rlang_0.4.12 grid_4.1.2
[49] nloptr_1.2.2.2 rstudioapi_0.13 rappdirs_0.3.3 htmlwidgets_1.5.4 [53] rmarkdown_2.10 boot_1.3-28 gtable_0.3.0 DBI_1.1.1
[57] R6_2.5.0 fastmap_1.1.0 utf8_1.2.2 rprojroot_2.0.2
[61] stringi_1.7.6 Rcpp_1.0.7 vctrs_0.3.8 tidyselect_1.1.1 [65] xfun_0.28