r - R knitr:将 spin() 与 R 和 Python 代码一起使用
问题描述
随着reticulate的出现,将 R 和 Python 结合在一个 .Rmd 文档中在 R 社区(包括我自己)中变得越来越流行。现在,我的个人工作流程通常从一个 R 脚本开始,在某些时候,我使用knitr::spin()
纯 .R 文档作为输入创建一个可共享的报告,以避免代码重复(另请参阅Knitr 的最佳隐藏宝石:旋转以了解更多关于话题)。
但是,一旦 Python 代码参与我的分析,我目前就被迫中断此工作流程并在编译报告之前将我的初始 .R 脚本手动转换(即复制和粘贴)为 .Rmd。我想知道,有没有人知道是否——或者就此而言,永远——可以knitr::spin()
在一个 .R 文件中同时使用 R 和 Python 代码块而不走这条弯路?我的意思是,就像在 .Rmd 文件中混合两种语言并在它们之间交换对象时一样。至少据我所知,engine = 'python'
目前不可能添加诸如旋转文档之类的东西。
解决方案
使用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 代码会丢失。
推荐阅读
- c++ - 从抽象祖父类重写非虚拟函数
- android - android webview客户端链接点击不起作用
- r - 如果列值不是 0 或 1,则删除整行
- mysql - 在 Ubuntu 服务器 20.4 LTS (AWS EC2) 上安装 Open Labyrinth 期间的问题
- powershell - 授予用户组:用户(localhost \ user)对具有power shell的文件夹的完全访问权限
- python - Python TypeError:参数必须是读写字节类对象,而不是字节
- java - 似乎它没有将值传递给参数 [Java]
- javascript - 如何为搜索功能添加“未找到值”?(谷歌应用脚本)
- c - Cmocka:如何模拟一个称为函数指针的函数
- docker - Docker - 在 MariaDB 中未经授权