对象转换

Type conversions
R Python
单元素向量 标量Scalar 1、 1LTRUE"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

reticulate::

Show the code
library(reticulate)
#devtools::install_version( "ggmap",  version = "3.5.2")

"R code"
Show the code
"python code"

R 安装 python 模块

reticulate:安装Python module

Show the code
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 模块

Show the code
# 调用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

Show the code
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
Show the code
### 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

Show the code
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
Show the code
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)