Interfaces/R/batch

From J Wiki
Jump to: navigation, search

R can be run in batch mode, with input/output using plain text files. A J application can call R by writing the plain text input file, calling R in batch mode, then reading any output files.


Installation

Install the stats/r addon.

Install R in the usual way, and ensure that the path to the R binary given at the top of the script is correct for your installation.

Load J, then:

   load 'stats/r/rdcmd'

   '' conew 'prdcmd'            NB. create connection instance

   Rcmdr 'rnorm(5)'
[1] -2.0071538 -1.5929521 -0.6619431  1.4306293  0.7228150

Methods

Methods are defined in z with names beginning R, for example Rcmd. These in turn call verbs in the connection locale, named without the R, for example Rcmd calls cmd in the connection locale.

Only a few basic methods are defined. It should be easy to extend these as required. Each method sends its argument as a command to R.

For most purposes, the standard output file has too much content, for example, it shows the session commands and session time. It is convenient to send the output from R commands to another file, and read that instead.

Plots can be generated and saved in a pdf file.

The methods are:

Rcmd - send command, ignore any output
Rcmdr - send command, return only command output
Rcmds - send command, return full session output
Rcmdp - send command, plot to pdf, ignore any output
Rcmdps - send command, plot to pdf, return full session output

Examples

   Rcmd 'array(1:6,c(2,3))'         NB. no output read

   Rcmdr 'array(1:6,c(2,3))'        NB. read command output only
     [,1] [,2] [,3]
[1,]    1    3    5
[2,]    2    4    6

   Rcmds 'array(1:6,c(2,3))'        NB. read all session output
> array(1:6,c(2,3))
     [,1] [,2] [,3]
[1,]    1    3    5
[2,]    2    4    6
> proc.time()
[1] 0.52 0.02 0.54 0.00 0.00
>

Several commands should be sent in a single character string, not one at a time (since the R session is opened and closed for each command). For example:

   Rcmdr 0 : 0
x = 1:5
y = c(2,3,5,7,11)
lsfit(x,y)
)

$coefficients
Intercept         X
     -1.0       2.2

$residuals
[1]  0.8 -0.4 -0.6 -0.8  1.0

$intercept
[1] TRUE

$qr
$qt
[1] -12.5219807   6.9570109  -0.9600727  -1.3426824   0.2747078

$qr
      Intercept          X
[1,] -2.2360680 -6.7082039
[2,]  0.4472136  3.1622777
[3,]  0.4472136 -0.1954395
[4,]  0.4472136 -0.5116673
[5,]  0.4472136 -0.8278950

...

The following sends a plot to a pdf file, showing the resulting session:

   Rcmdps 'plot(c(2,3,5,7,11),type="l")'
> pdf(file="/home/chris/j601/temp/r.pdf")
> plot(c(2,3,5,7,11),type="l")
> proc.time()
[1] 0.54 0.02 0.56 0.00 0.00
>

Source Code

The source code is in the public subversion respository, subdirectory r/dcmd.