---
execute:
eval: false
---
# R⬌Python {.unnumbered}
## 对象转换
| R | Python | 例 |
|------------------------|------------------------|------------------------|
| 单元素向量 | 标量Scalar | `1`、 `1L`、`TRUE`、`"foo"` |
| 未命名列表或多元素向量 | List | `c(1.0, 2.0, 3.0)`, `c(1L, 2L, 3L)` |
| 命名列表 | Dict | `list(a = 1L, b = 2.0)`, `dict(x = x_data)` |
| Matrix/Array | NumPy ndarray | `matrix(c(1,2,3,4), nrow = 2, ncol = 2)` |
| Data Frame | Pandas DataFrame | `data.frame(x = c(1,2,3), y = c("a", "b", "c"))` |
| Function | Python function | `function(x) x + 1` |
| NULL, TRUE, FALSE | None, True, False | `NULL`, `TRUE`, `ALSE` |
: Type conversions
## [`reticulate::`](https://rstudio.github.io/reticulate/index.html){.uri}
```{r}
#| comment: "#>"
library(reticulate)
#devtools::install_version( "ggmap", version = "3.5.2")
"R code"
```
```{r}
#| comment: "###>"
"python code"
```
### **R 安装 python 模块**
[reticulate:安装Python module](https://rstudio.github.io/reticulate/articles/python_packages.html)
```{r eval=FALSE}
#| comment: "#>"
library(reticulate)
py_config()
py_module_available('pip')
# Anaconda 激活环境 pip install scanpy -i https://pypi.tuna.tsinghua.edu.cn/simple/ ,依赖包含 numpy pandas
py_module_available('numpy')
py_module_available('pandas')
py_module_available('scanpy')
reticulate::repl_python()
```
### R 调用 Python 模块
```{r eval=FALSE}
#| comment: "#>"
# 调用os模块(module)的listdir()函数
os <- reticulate::import("os")
os$listdir("./")
# 调用seaborn模块的load_dataset()函数
# 需要seaborn模块已安装
sns <- import("seaborn")
tips <- sns$load_dataset("tips")
print(head(tips))
```
### **R** → Python
```{r}
#| comment: "#>"
A <- 1
B <- c(1, 2, 3)
C <- c(a = 1, b = 2, c = 3)
D <- matrix(1:4, nrow = 2)
E <- data.frame(a = c(1, 2), b = c(3, 4))
G <- list(1, 2, 3)
H <- list(c(1, 2), c(3, 4))
I <- list(a = c(1, 2), b = c(3, 4))
J <- function(a, b) {
return(a + b)
}
K1 <- NULL
K2 <- T
K3 <- F
```
```{python}
### float
r.A
type(r.A)
### list
r.B
type(r.B)
r.C
type(r.C)
### numpy.ndarray
r.D
type(r.D)
### pandas.core.frame.DataFrame
r.E
type(r.E)
### list
r.G
type(r.G)
r.H
type(r.H)
### dict
r.I
type(r.I)
### function
r.J
type(r.J)
r.J(2, 3)
### NoneType
r.K1
type(r.K1)
### bool
r.K2
type(r.K2)
r.K3
type(r.K3)
```
### **Python** → R
```{python}
import pandas as pd
m = [1, 2, 3]
n = pd.DataFrame([[1, 2], [3, 4]], columns=["a", "b"])
A = 1
B = [1, 2, 3]
C = [[1, 2], [3, 4]]
D1 = [[1], 2, 3]
D2 = [[1, 2], 2, 3]
E = (1, 2, 3)
FF = ((1, 2), (3, 4))
G = ((1, 2), 3, 4)
H = {"a": [1, 2, 3], "b": [2, 3, 4]}
I = {"a": 1,"b": [2, 3, 4]}
def J(a, b):
return a + b
```
```{r}
#| comment: "#>"
py$m
py$n
### integer
py$A
class(py$A)
py$B
class(py$B)
### list
py$C
class(py$C)
py$D1
class(py$D1)
py$D2
class(py$D2)
py$E
class(py$E)
py$FF
class(py$FF)
py$G
class(py$G)
py$H
class(py$H)
py$I
class(py$I)
### function
py$J
class(py$J)
py$J(2, 3)
```