使用reticulate::source_python
可能是一种解决方案。
例如,这是一个简单的 .R 脚本,它将被旋转为 .Rmd,然后呈现为 .html
旋转我
#'---
#'title: R and Python in a spin file.
#'---
#'
#' This is an example of one way to write one R script, containing both R and
#' python, and can be spun to .Rmd via knitr::spin.
#'
#+ label = "setup"
library(nycflights13)
library(ggplot2)
library(reticulate)
use_condaenv()
#'
#' Create the file flights.csv to
#'
#+ label = "create_flights_csv"
write.csv(flights, file = "flights.csv")
#'
#' The file flights.py will read in the data from the flights.csv file. It can
#' be evaluated in this script via source_python(). This sould add a data.frame
#' called `py_flights` to the workspace.
source_python(file = "flights.py")
#'
#' And now, plot the results.
#'
#+ label = "plot"
ggplot(py_flights) + aes(carrier, arr_delay) + geom_point() + geom_jitter()
# /* spin and knit this file to html
knitr::spin(hair = "spin-me.R", knit = FALSE)
rmarkdown::render("spin-me.Rmd")
# */
蟒蛇文件是
航班.py
import pandas
py_flights = pandas.read_csv("flights.csv")
py_flights = py_flights[py_flights['dest'] == "ORD"]
py_flights = py_flights[['carrier', 'dep_delay', 'arr_delay']]
py_flights = py_flights.dropna()
生成的 .html 的屏幕截图是:

编辑如果必须将所有内容保存在一个文件中,那么在source_python
调用之前您可以创建一个 python 文件,例如,
pycode <-
'import pandas
py_flights = pandas.read_csv("flights.csv")
py_flights = py_flights[py_flights["dest"] == "ORD"]
py_flights = py_flights[["carrier", "dep_delay", "arr_delay"]]
py_flights = py_flights.dropna()
'
cat(pycode, file = "temp.py")
source_python(file = "temp.py")
我的观点:将 python 代码放在自己的文件中比在 R 脚本中创建更好,原因有两个:
- 更容易重用python代码
- 当我的 IDE 中的语法高亮显示为字符串而不是在其自己的文件中时,python 代码会丢失。