Chapter 15: Python

15.1 using Python in R / RMarkdown

https://bookdown.org/yihui/rmarkdown/language-engines.html

names(knitr::knit_engines$get())
##  [1] "awk"         "bash"        "coffee"      "gawk"        "groovy"     
##  [6] "haskell"     "lein"        "mysql"       "node"        "octave"     
## [11] "perl"        "php"         "psql"        "Rscript"     "ruby"       
## [16] "sas"         "scala"       "sed"         "sh"          "stata"      
## [21] "zsh"         "asis"        "asy"         "block"       "block2"     
## [26] "bslib"       "c"           "cat"         "cc"          "comment"    
## [31] "css"         "ditaa"       "dot"         "embed"       "eviews"     
## [36] "exec"        "fortran"     "fortran95"   "go"          "highlight"  
## [41] "js"          "julia"       "python"      "R"           "Rcpp"       
## [46] "sass"        "scss"        "sql"         "stan"        "targets"    
## [51] "tikz"        "verbatim"    "theorem"     "lemma"       "corollary"  
## [56] "proposition" "conjecture"  "definition"  "example"     "exercise"   
## [61] "hypothesis"  "proof"       "remark"      "solution"

https://rstudio.github.io/reticulate/articles/python_packages.html

x = 'hello, python world!'
print(x.split(' '))
## ['hello,', 'python', 'world!']
library(reticulate)
virtualenv_python()
library(reticulate)
# conda_list()
library(reticulate)
virtualenv_list()

https://rstudio.github.io/reticulate/reference/install_python.html

library(reticulate)
version <- "3.9.12"
# install_python(version)

## create a new environment
# virtualenv_create("r-reticulate", version = version)

# use_virtualenv("r-reticulate")

## install MatPlotLib
# virtualenv_install("r-reticulate", "matplotlib")

## import MatPlotLib (it will be automatically discovered in "r-reticulate")
matplotlib <- import("matplotlib")

copy C:\Users\RW\AppData\Local\r-reticulate\r-reticulate\pyenv\pyenv-win\versions\3.9.12\tcl\tcl8.6 and C:\Users\RW\AppData\Local\r-reticulate\r-reticulate\pyenv\pyenv-win\versions\3.9.12\tcl\tk8.6 two folders to the folder C:\Users\RW\AppData\Local\r-reticulate\r-reticulate\pyenv\pyenv-win\versions\3.9.12\Lib

# library(reticulate)
# use_virtualenv("r-reticulate")
# # matplotlib <- import("matplotlib")
# matplotlib$use("Agg", force = TRUE)
import matplotlib.pyplot as plt
plt.plot([0, 2, 1, 4])
plt.show()

15.3 list comprehension

https://www.sololearn.com/en/learn/courses/python-intermediate/lesson/1188906590?p=1

cubes = [i**3 for i in range(5)]

print(cubes)

 

## [0, 1, 8, 27, 64]

15.4 functional programming

  • pure function
  • lambda
  • map
  • filter
  • generator
  • decorator
  • recursion
  • *args
  • **kwargs

15.5 object-oriented programming = OOP

  • class
  • inheritance
  • magic method
  • operator overloading
  • data hiding
  • static method
  • property