reticulate 의 출현과 함께 R과 Python을 단일 .Rmd 문서로 결합하는 것이 R 커뮤니티에서 점점 인기를 얻고 있습니다 (자신도 포함). 이제 내 개인 워크 플로는 일반적으로 R 스크립트로 시작하고, 어느 시점에서 knitr::spin()
코드 중복을 피하기 위해 일반 .R 문서를 입력으로 사용하여 공유 가능한 보고서를 만듭니다 ( Knitr의 최고의 숨겨진 보석 : 자세한 내용은 스핀 참조). 이야기).
그러나 Python 코드가 분석에 포함 되 자마자 현재이 워크 플로를 중단하고 보고서를 컴파일하기 전에 초기 .R 스크립트를 .Rmd로 수동으로 변환 (예 : 복사 및 붙여 넣기)해야합니다. knitr::spin()
이 우회를하지 않고 단일 .R 파일에서 R 및 Python 코드 청크를 모두 사용할 수 있는지 여부를 아는 사람이 있는지 궁금합니다 . .Rmd 파일에서 두 언어를 혼합하고 두 언어간에 객체를 교환 할 때 작동하는 것처럼 작동합니다. 적어도 내가 아는 engine = 'python'
한 현재로서는 문서를 돌리는 것과 같은 것을 추가 할 가능성이 없습니다 .
의 사용은 reticulate::source_python
하나의 해결책이 될 수 있습니다.
예를 들어 다음은 .Rmd로 회전 한 다음 .html로 렌더링되는 간단한 .R 스크립트입니다.
스핀 미 R
#'---
#'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")
# */
파이썬 파일은
flights.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
호출 하기 전에 파이썬 파일을 만들 수 있습니다. 예 :
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")
내 의견 : 파이썬 코드를 자체 파일에 포함하는 것이 두 가지 이유로 R 스크립트에서 생성하는 것보다 낫습니다.
이 기사는 인터넷에서 수집됩니다. 재 인쇄 할 때 출처를 알려주십시오.
침해가 발생한 경우 연락 주시기 바랍니다[email protected] 삭제
몇 마디 만하겠습니다