Alter file.show() behaviour - r

I'm running file.show() in RStudio on a Mac, like this:
filename <- "/Users/me/reports/myfile.pdf" # replace with file location/name
file.show(file.path(filename), title="My File")
This does two things:
Opens my file.pdf
Opens a blank file in RStudio called "My File".
options()$pdfviewer
returns:
"/usr/bin/open"
How can I stop (2) from happening?

If you want to simply open a PDF file via RStudio on a Mac, the simplest way (as far as I know) is to use the system function:
filename <- "/Users/me/reports/myfile.pdf"
pdf <- getOption("pdfviewer") # same as options()$pdfviewer
cmd <- paste(pdf,filename)
system(cmd)
For example it is used by openPDF in Biobase (see here)
I don't know a way to alter the file.show behaviour in order to prevent a blank file being opened in RStudio. I think it has something to do with The R.app Mac OS X GUI uses its internal pager irrespective of the setting of pager. that you can see on the manual here.
Note: it is different on a Windows machine, use shell.exec(filename) directly.

Related

How to run Python, R, Octave or Julia using BowPad?

I try using a very light-weighted editor BowPad to edit and run codes.
Take running R as an example, which has been added to Windows PATH Environment Variable D:\R\R-3.6.2\bin\x64
I try to take some following steps:
I built a test.r writing some testing line codes as 1+2; plot(1:10)
Menu --> Run --> Configure custom commands
Command Name: run R
Command Line: D:\R\R-3.6.2\bin\R.exe $(SEL_TEXT)
$(LINE) The line where the cursor is
$(POS) the position where the cursor is
$(TAB_PATH) the path to the file of the active tab
$(TAB_NAME) the file name without extension of the current tab
$(TAB_EXT) the file extension of the current tab
$(TAB_DIR) the directory of the file of the active tab
$(SEL_TEXT) the selected text or the word at the cursor position
$(SEL_TEXT_ESCAPED) like $(SEL_TEXT) but escaped, useful for urls
When I press to choose run R to run the code, something wrong happens!
It will open a Rterm(64-bit) window each time when I run R!
it shows RGUMENT '1+2' __ignored__ or ARGUMENT 'plot(1:10)' __ignored__
Did I missing something ? BTW, can we set some shortcuts keys for running Python, R, Octave or Julia?
Also, when I reach the homepage of BowPad for more information, little usage of this software can be found!
R.exe refers to Rterm. You can use Rgui.exe instead but that won't automatically process arguments. I think what you likely want is to send the selected text to a running R session rather than starting up a new R session each time.
To do that
download this file and optionally place it on your path https://raw.githubusercontent.com/ggrothendieck/batchfiles/master/clip2r.js
in the Bowpad Run | Configure window configure a Run R command as the following (or if clip2r.js is not on your path use the entire pathname). It should be just like this with no arguments.
clip2r.js
From the Windows cmd line if Rgui is running we see that tasklist | findstr Rgui finds Rgui as the R gui process and you can create additional js scripts by editing clip2r.js replacing Rgui in the js script with whatever is the appropriate word to locate python, julia, octave or other R front end assuming again that they are running.
Now to invoke it from within Bowpad:
ensure that your Rgui session is already running and
from within Bowpad select the code you want to run and copy it to the clipboard and then invoke Run R. For example, to run everything use ctrl A ctrl C ctrl R 0 assuming that Run R is in position 0 in the configure menu. Alternately use the mouse with the Ribbon.
Regarding the comment about difficulty finding help, it looks like Bowpad is based on Scintilla so the documentation for it and the related SciTE editor likely apply to Bowpad too. You can also check the Bowpad source code on github.

Why does RMarkdown `render` behavior depend on whether it's called from RStudio Server or from a PHP shell?

I have an RMarkdown document that includes 'special characters', such as ë. If I render the document using RStudio Server's "knit document" button, it renders fine. When I render it by using the RStudio Server button to source another R script that calls RMarkdown's render function, it also renders fine.
However, from some reason that's beyond me (but hopefully not for long), I get different results when that same R script is called by index.php using:
$results = shell_exec("R --file='/home/username/public_html/some/subdirectories/process.R' --no-save 2>&1");
When I do this, in the resulting .html file, the special symbols (I guess the unicode symbols) are replaced by <U+00EB>. I've tried to look up whether this is some kind of variation of HTML elements that I didn't know about yet, but I have been unable to find anything about this.
(note: any link to a place where I can learn more about this (and, while we're at it, why my browser doesn't show it as, for example, the ë it represents, is also greatly appreciated!)
Reproducable example
Contents of example.php:
<?php
shell_exec("R --file='/home/username/public_html/subdirectory/example.R' --no-save 2>&1");
?>
Contents of example.R (this is what I needed on my server):
workingPath <- "/home/username/public_html/subdirectory";
### Set path to RStudio's pandoc version
Sys.setenv(PATH=paste(Sys.getenv("PATH"),
"/usr/lib/rstudio-server/bin/pandoc",
sep=":"));
### Set HOME and LANG
Sys.setenv(HOME = '/home/username');
Sys.setenv(LANG = 'en_US.UTF-8');
require(rmarkdown);
renderResults <-
render(file.path(workingPath, 'example.Rmd'),
output_file = file.path(workingPath, 'example.html'),
intermediates_dir = file.path(workingPath, 'tmp'),
encoding="UTF-8");
Contents of example.Rmd:
---
title: 'Reproducable example'
output: html_document
---
```{r}
cat("This is an ë symbol.");
```
Results of this example:
When I run this from R Studio, I get:
cat("This is an ë symbol.");
## This is an ë symbol.
When I run this from PHP, I get:
cat("This is an ë symbol.");
## This is an <U+00EB> symbol.
(note how, interestingly, the echo'ed ë does show up normally...)
I now resorted to doing a str_replace in the index.php file, but that's not ideal.
I've checked the render manual, but I can't find anything about this behavior.
I've also looked at specifying options for pandoc in the YAML header of the .Rmd file, but the only thing that seems to come close is the --ascii option, and that doesn't do anything. The R Studio RMarkdown page doesn't provide any hints, either.
Could it perhaps have to do with environment variables that are set in RStudio? I already had to set:
Sys.setenv(HOME = '/home/oupsyusr');
Sys.setenv(LANG = 'en_US.UTF-8');
in the R script to get Pandoc going in the first place when called in the R script called from the PHP shell; but if this is the problem, how can I figure out which settings RStudio sets to which values, or more accurately, which of those are important? I ran:
Sys.getenv()
From within R Studio, and that shows quite a list. I recognize none of the entries as having to do with encoding or so.
Or, does knitr cause this? When I store and inspect the .md file, the Unicode element things already show up. However, the knitr help page with chunk options doesn't say anything about unicode or encoding in general.
Does anybody know where this is documented, or does anybody happen to have encountered this situation before?
I'm running RStudio 0.99.903 and R 3.3.1 on CentOS 6.8.
Usually, issues of this form (where unicode characters are converted to a unicode code point representation, e.g. <U+00EB> in this case) are caused by an attempt to run R within a non-UTF-8 locale.
Typically, this can be verified by checking the output of Sys.getlocale("LC_ALL"). If you see a C locale reported, then you likely need to enforce a UTF-8 locale with something like:
Sys.setlocale("LC_ALL", "en_US.UTF-8")
substituting the particular UTF-8 locale flavor based on your desired language. (For reference, the set of available locales can usually be queried from a terminal with something like locale -a).

Sourcing script does not print any output to the console

I am using Ubuntu inside Windows XP using VirtualBox, and I installed R properly. I am using a library called psych for this. The following is my code:
impact <- read.table("stats1.ex.02.txt", header=T)
class(impact)
describe(impact)
I am taking Statistics One course on coursera.org and the Prof gives this txt file to work with. When I run this in R, using source("test.R") (where test.R is the filename I gave),
nothing happens. What could be problem here ?
Try using source("test.R", echo=TRUE) or adding print to whatever you want printed after sourcing your script. Thus, your script might be:
impact<- read.table("stats1.ex.02.txt",header=T)
print(class(impact))
print(describe(impact))

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)

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