Wolfram website What's New? has quite a few cool examples of new features. We are interested here in
Using Higher-Order Functions and Closures to Structure Code: Flexible Plotting Routines
I will give it here to apply to your specific code.
"This example illustrates some means of code composition supported by RLink, which allow smooth and productive combined R-Mathematica workflows. Load RLink."
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."
mathematicaRPlotWrapper = RFunction["function(filename, plotfun){
pdf(filename)
plotfun()
dev.off()
}"];
"Create a Mathematica counterpart wrapper that automates file import and adds error-checking."
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]];
Now, the above functions worked with all examples I tried. So I will apply it to your specific case here:
Show[#, ImageSize -> Medium, PlotRange -> All] &@
getRPlot[RFunction["function(){
x <- 1:5
y1 <- rnorm(5)
y2 <- rnorm(5,20)
par(mar=c(5,4,4,5)+.1)
plot(x,y1,type=\"l\",col=\"red\")
par(new=TRUE)
plot(x,y2,,type=\"l\",col=\"blue\",xaxt=\"n\",yaxt=\"n\",xlab=\"\"\
,\ ylab=\"\")
axis(4)
mtext(\"y2\",side=4,line=3)
legend(\"topleft\",col=c(\"red\",\"blue\"),lty=1,legend=c(\"y1\",\
\"y2\"))
}"]]
