Call R plots from c++ using RInside/ Rcpp - r

Is it possible to call the plot functions from the c++ ?
Currently when I try to do that, the ubuntu terminal sort of freezes for sometime ( may be the duration for which the 3d plot would be created and then rotated for a full 360 degrees) and then unfreezes, without ever popping a new window.
Is this the expected behavior or is there something that I am doing wrong ? How can I get the plots ( R graphics ) to run from within c++ using rinside and rcpp ?
Thnx
-Egon

Yes, there is a working examples in the Rcpp package. Look at the file functionCallback/newApiExample.r in the examples/ directory.
You may need to experiment with sleep() to 'hold' the plot for a moment, or plot to a file and then have the file displayed. It all depends but you gave little detail.

The environment variable which deals with the interactive session is R_INTERACTIVE_DEVICE.
We need to create a file named .Renviron in our home directory, and then add the following code to that file:
R_INTERACTIVE_DEVICE = X11 for Linux based systems.
anisha#linux-y3pi:~> ls .Renviron
.Renviron
anisha#linux-y3pi:~> cat .Renviron
R_INTERACTIVE_DEVICE = X11a
References:
1. http://stat.ethz.ch/R-manual/R-patched/library/base/html/Startup.html
2. http://stat.ethz.ch/R-manual/R-patched/library/base/html/options.html

Related

Make R project Automatically open Specific Scripts

I am working in team, we mainly use R, I am quite used to use R project in Rstudio, which I like because when I open them I have all my scripts and everything at the right place. However when another member of the team opens one of my project it loads the values and data but does not open the R script (one can see that by physically clicking on the project through the windows explorer rather than using the menu at the top right in R). I guess something can be done in the .Rprofile but I did not find any command to open physically a script, I tried
file.edit("./Main.R")
but it did not open anything. It just got me the message :
Error: could not find function "file.edit"
As always,
Thanks for your help !
**EDIT
I tried to use
file.show
file.edit
shell.exec(file.path(getwd()), "Main.R"))
in the .Rprofile. Nothing worked.
Romain
You can use the following code in the .Rprofile file.
setHook("rstudio.sessionInit", function(newSession) {
if (newSession)
rstudioapi::navigateToFile('<file name>', line = -1L, column = -1L)
}, action = "append")
The rstudioapi library has the function navigateToFile to open a file in Rstudio. The problem is that the code in the .Rprofile runs before Rstudio initialization. To deal with this problem you can use the setHook function (from base package) to make the code execute after the Rstudio initialization.
file.edit requires the utils package
library(utils)
file.edit("Master.R")
However, if it opens in Notepad rather than RStudio you have the same problem as me. I've tried editing the editor= in all possible places: .RProfile, RProfile, RProfile.sites, with and without .First() function statements and calls. However, RStudio does not load the .R file in RStudio if told to. It may be linked to the .RData file being loaded after .RProfile. Bug? Or at least a feature RStudio should incorporate in their RProject file specification.

How do I make R run R Commander every time it starts up?

I used to have it set up that R commander plug-in would start up automatically every time I opened the R application, but I've upgraded R and can't remember how I did it.
Here is Scott Hyde's instructions for creating a shortcut to start R commander every time you start R.
Open up the C:\Program Files\R\R-2.10.1\etc (or similarly named version directory).
Edit the file Rprofile.site and add the following lines. The mylibs variable is a list of packages that you want starting up each time you run Rcmdr. Both lattice and MASS are depencies of Rcmdr and need to be loaded. If you load them this way, they are loaded SILENTLY!
defpack = getOption("defaultPackages")
mylibs = c("tcltk","car","lattice","MASS","Matrix")
if(Sys.getenv("RCMDR") == "TRUE") mylibs = c(mylibs,"Rcmdr")
options(defaultPackages = c(defpack,mylibs))
Next, copy the shortcut that is used to run R onto the Desktop. Right click on the file, and select properties Add the following to the end of the "Target:"
"C:\Program Files\R\R-2.10.1\bin\Rgui.exe" --sdi RCMDR=TRUE
Notice that the options are OUTSIDE of the quotation marks.
Change the name of the shortcut you just made to "Rcmdr"
Double click on it, and both R and Rcmdr start!
Recently started using R, and I was testing out the other solution given by #user123943, and it just couldn't seem to work out right. Thought maybe there'd be a simpler solution and tried it and it worked fine. All you need to do is:
Find the Rprofile.site file (it should be in an etc file somewhere inside your R program file) (e.g.: C:\Program Files\R\R-4.1.1\etc)
Edit the file (give yourself permissions to edit if required) by adding in library(Rcmdr) at the end of the file.
That's it! Quick and easy solution! If you decide to revert it back all you will need to do is remove the added code at the end of the Rprofile.site file :)
Of course, save the file before opening up R again!

Starting R and calling a script from a batch file

I have an R-based GUI that allows some non-technical users access to a stats model. As it stands, the users have to first load R and then type loadGui() at the command line.
While this isn't overly challenging, I don't like having to make non-technical people type anything at a command line. I had the idea of writing a .bat file (users are all running Windows, though multi-platform solutions also appreciated) that starts R GUI, then autoruns that command.
My first problem is opening RGui from the command line. While I can provide an explicit path, such as
"%ProgramW6432%\R\R-2.15.1\bin\i386\Rgui.exe"
it will need updating each time R is upgraded. It would be better to retrieve the location of RGui from the %path% environment variable, but I don't know an easy way to parse that.
The second, larger problem is how to call commands for R on startup from the command line. My first thought is that I could take a copy of ~/.Rprofile, append the extra command, and then replace the original copy of the file once R is loaded. This is awfully messy though, so I'd like an alternative.
Running R in batch mode isn't an option, firstly since I can't persuade GUIs to display themselves, and secondly because I would like the R console available, even if the users shouldn't need to use it.
If you want a toy GUI to test your ideas, try this:
loadGui <- function()
{
library(gWidgetstclck)
win <- gwindow("test")
rad <- gradio(letters[1:3], cont = win)
}
Problem 1: I simply do not ever install in the suggested default directory on Windows, but rather group R and a few related things in, say, c:/opt/ where I install R itself in, say,c:/opt/R-current so that the path c:/opt/R-current/bin will remain constant. On upgrade, I first renamed to R-previous and then install into a new R-current.
Problem 2: I think I solved that many moons ago with scripts. You can now use Rscript.exe to launch these, and there are tcltk examples for waiting for a prompt.
I have done similar a couple of times. In my cases the client was using windows so I just installed R on their computer and created a shortcut on their desktop to run R. Then I right click on the shortcut and choose properties to get the propertiest dialog. I then changed the "Start in" folder to the one where I wanted it to run from (which had the .Rdata file with the correct data and either a .First function in the .Rdata file or .Rprofile in the folder). There is also a "Run:" option that has a "Minimized" option to run the main R window minimized.
I had created the functions that I wanted to run (usually a specialized gui using tcltk) and any needed data and saved them in the .Rdata file and also either created .First or .Rprofile to run the comnand that showed the gui. The user double clicks on the icon on the desktop and up pops my GUI that they can work with while ignoring the other parts.
Take a look at the ProjectTemplate library. It does what you want to do. It loads used libraries from a batch file an run R files automatically after loading as well as a lot of other usefull stuff as well...
Using the answer from https://stackoverflow.com/a/27350487/41338 and a comment from Richie Cotton above I have arrived at the following solution to keeping a script alive until a window is closed by checking if the pointer to the window is valid.
For a RGtk2 window created and shown using:
library(RGtk2)
mainWindow <- gtkWindow("toplevel", show = TRUE)
Create a function which checks if the pointer to it exists:
isnull <- function(pointer){
a <- attributes(pointer)
attributes(pointer) <- NULL
out <- identical(pointer, new("externalptr"))
attributes(pointer) <- a
return(out)
}
and at the end of your script:
while(!isnull(mainWindow)) Sys.sleep(1)

plotting data in R from matlab

I was wondering if it is possible to work between matlab and R to plot some data. I have a script in matlab which generates a text file. From this I was wondering if it was possible to open R from within matlab and plot the data from this text file and then return to matlab.
For example, if I save a text file called test.txt, in the path 'E:\', and then define the path of R which in my case will be:
pathR = 'C:\Program Files\R\R-2.14.1\bin\R';
Is it possible to run a script already written in R saved under test1.R (saved in the same directory as test.txt) in R from matlab?
If you're working with Windows (from the path it looks like you are), you can use the MATLAB R-link from the File Exchange to pass data from Matlab to R, execute commands there, and retrieve output.
I don't use R so this is not something I have done but I see no reason why you shouldn't be able to use the system function to call R from a Matlab session. Look in the product documentation under the section Run External Commands, Scripts, and Programs for this and related approaches.
There are some platform-specific peculiarities to be aware of and you may have to wrestle a little with what is returned (though since you are planning to have R create a plot which is likely to be a side-effect rather than what is returned you may not). As ever this is covered quite well in the product's documentation
After using R(D)COM and Matlab R-link for a while, I do not recommend it. The COM interface has trouble parsing many commands and it is difficult to debug the code. I recommend using a system command from Matlab as described in the R Wiki. This also avoids having to install RAndFriends.

Disable GUI, graphics devices in R

Is there an easy way to turn of all GUI elements in R and run it solely from the command line on OSX?
I'm trying to replicate the behavior of a remote linux terminal on my OSX machine. Thus plot() should just save a file and things like CRAN mirror selection should be text, not a Tk interface. I'm having trouble finding where to set this behavior.
I had this exact question and wanted a way to do it without changing my existing code. I usually run with graphics support but sometimes I'll run a script on the server for a larger dataset and then I just want the plots to be output somewhere automatically.
In Dirk's answer Ian Fellows gives the simple solution. On the command line in R type:
options(device=pdf)
And then any plots will be written to the current directly to an Rplots.pdf file.
If you want the files to not be plotted at all then use
options(device=NULL)
For the plots you can just direct the output to a file using the pdf() command (or png(), jpeg()...).
I don't own an OS X box, but did you try to unset the X11 environment variable DISPLAY:
DISPLAY="" R --vanilla
When I do that on Linux and query R for capabilties(), x11 comes up as FALSE as desired.
I don't run OSX but you could attempt to run R from the Terminal application, rather than the Mac OSX launcher, and see whether that runs as you need.
As Matti writes, you can send output to files using the following commands; but I don't know if that's really the substance of your question.
png("pngfile.png")
plot(foo)
title(main="bar")
dev.off()
So instead of the quartz graphical object, your output goes to the file.
Similarly, you can output what would normally appear in the terminal to a file.
sink("foo.file")

Resources