%load_ext rpy2.ipython
%%R
A <- matrix(1, 15, 15)
A[4,7] <- 0
persp(A, expand=0.5)
如果用 %%R 是整個 cell 給 R。但只有一句話要給 R, 我們可以用 %R。
%R print("Hi from R")
print("Hi from Python")
[1] "Hi from R"
Hi from Python
本來 Python 是沒有 A 的。
A
--------------------------------------------------------------------------- NameError Traceback (most recent call last) <ipython-input-4-bf072e911907> in <module>() ----> 1 A NameError: name 'A' is not defined
向 R 要 A!!
%R -o A
A
<Matrix - Python:0x10af1f368 / R:0x101703400> [1.000000, 1.000000, 1.000000, ..., 1.000000, 1.000000, 1.000000]
A.dim
<IntVector - Python:0x10af1ccf8 / R:0x107f1a468> [ 15, 15]
很容易轉成 numpy 的 array, 形式保留。
from numpy import array
A = array(A)
A.shape
(15, 15)
from numpy import linspace, sin
x = linspace(0, 10 , 100)
y = sin(x) + 0.5*x
%R -i x
%R -i y
%R plot(x,y)