« View all new features in
Mathematica
9
◄
previous
|
next
►
New in
Mathematica
9
›
Built-in Integration with R
Using Higher-Order Functions and Closures to Structure Code: Flexible Plotting Routines
This example illustrates some means of code composition supported by
RLink
, which allow smooth and productive combined R-
Mathematica
workflows.
Load
RLink
.
In[1]:=
X
Needs["RLink`"] InstallR[]
The following creates a generic R wrapper that creates the plot and saves it to a file, and defines certain parameters for the resulting image.
In[2]:=
X
mathematicaRPlotWrapper = RFunction["function(filename, plotfun){ pdf(filename) plotfun() dev.off() }"]
Out[2]=
Create a
Mathematica
counterpart wrapper that automates file import and adds error-checking.
In[3]:=
X
Clear[getRPlot]; getRPlot[plotFun_RFunction] := With[{tempfile = FileNameJoin[{$TemporaryDirectory, "temp.pdf"}]}, If[FileExistsQ[tempfile], DeleteFile[tempfile]]; mathematicaRPlotWrapper[tempfile, plotFun]; If[! FileExistsQ[tempfile], Return[$Failed]]; Import[tempfile] ];
Display the result.
In[4]:=
X
Show[#, ImageSize -> Medium, PlotRange -> All] &@ getRPlot[ RFunction["function(){ x<- seq(1,10,0.1) y<- sin(x) plot(y~x) }"]]
Out[4]=