R에서 파이썬 코드를 실행할 수있는 reticulate 패키지가 편리합니다.

8137 단어 R파이썬reticulate

배경



"Rstudio에서 Python 사용"에서 언급했듯이 Rstudio에서 쉽게 Python을 실행할 수 있습니다. 이것만으로도 편리합니다만, R과 Python의 제휴, 예를 들면 「Python의 라이브러리로 구한 결과를 R 객체로서 격납해, ggplot2로 작도한다」할 수 있으면 좋다. reticulate는 이것을 가능하게하는 R 패키지입니다.

참고 : How to Run Python from R Studio

환경



PC: MacBook Pro 2020
OS: macOS Catalina (10.15.5)
R : 4.0.2 (2020-06-22)
RStudio: 1.4.1103
reticulate: 1.18

방법·결과



1. reticulate 패키지 다운로드, 로드



일반적인 R 패키지와 마찬가지로 install.packages() 와 library() 를 사용합니다.
install.packages("reticulate")
library(reticulate)

2. 파이썬 라이브러리 가져오기



reticulate::import() 를 사용하여 Python 라이브러리를 로드합니다. 변수에 저장하여 이름을 지정할 수도 있습니다.
np <- reticulate::import("numpy") #「import numpy as np」と同義
plt <- reticulate::import("matplotlib.pyplot")

3. 가져온 라이브러리 사용



파이썬에서는 '.'로 메소드를 사용하지만 R에서 읽으면 '$'로 메소드를 사용할 수 있습니다. 여기서는 numpy를 사용하여 난수를 생성합니다. 인수의 형태를 명시하지 않으면 에러가 되는 일이 있으므로 주의가 필요합니다.
아래의 예에서는 int형을 입력해야 하는 부분이 float형으로 되어 있으면 에러가 나와 있습니다. 그 때문에, as.integer()로 int형인 것을 명시합니다(R의 경우는 숫자의 뒤에 「L」를 붙이면 int형으로서 인식하기 때문에 「100L」에서도 움직입니다).
참고 : reticulate does not work with R-Data frame and fit() function from Python
#乱数を生成、メソッドを使用するには「$」、引数の型を明示
x <- np$random$rand(as.integer(100))
y <- np$random$rand(as.integer(100))

# 引数の型を明示しないとエラーになる
np$random$rand(100)
# py_call_impl(callable, dots$args, dots$keywords) でエラー: 
# TypeError: 'float' object cannot be interpreted as an integer

4. 산점도 그리기



matplotlib로 산점도를 그려 R png 함수로 저장합니다.
png("scatter_py.png")
plt$scatter(x, y)
plt$title("Title")
plt$xlabel("x")
plt$ylabel("y")
plt$show()
dev.off()



5. ggplot2로 그리기



도면은 R의 ggplot2를 사용하는 경우가 많기 때문에 numpy에서 생성한 난수를 ggplot2로 그려 보겠습니다.
d <- data.frame(x = x, y = y)

png("scatter_r.png")
ggplot(data = d, aes(x = x, y = y)) +
        geom_point()
dev.off()



6. 파이썬 코드로드



자체 제작 파이썬 코드를 로드할 수도 있습니다. 실행할 때 "Hello R!"라고 표시하는 helloR.py를 만들었습니다.
def helloR():
        print("hello R!")

source_python()으로 helloR 함수를 읽습니다.
reticulate::source_python("helloR.py")
helloR()
# hello R!

보충



사용하는 python 인터프리터는 도입한 방법에 따라 use_condaenv(), use_virtualenv(), use_python()로 지정합니다.
Rstudio1.4 이상에서는 Tools -> Global Options의 Python에서 선택한 인터프리터가 기본적으로 선택되어있는 것 같습니다.

좋은 웹페이지 즐겨찾기