help for rsource(Roger Newson)

Run R from inside Stata using an R source file and/or inline R code

rsource
[ using R_source_filename ] [ ,
terminator(string)
maxlines(#)
noloutput lsource
rpath(R_pathname)
roptions(R_options)
]

where R_source_filename is the name of a file containing R source code,
R_pathname is the name of the path of the R command to be used under the user's system,
and R_options is a set of options for the R command.

Description

rsource runs an R source program,
from an inline sequence of lines and/or from a file,
in batch mode from within Stata,
optionally listing the R output and/or the R source code
to the Stata Results window and/or the Stata log file.
This allows the user to call R at a point in the execution of a Stata program
to input data files previously created by Stata
and/or to create output data files for later input by Stata.
The R software system must be installed on the user's system if the rsource package is to work.

Options for use with rsource

terminator(string) specifies a string,
to be used as a terminator for an inline R program inside the Stata program.
If terminator() is specified,
then rsource reads lines of R code from the following lines of the Stata program,
until it encounters a line containing only the terminator() string,
or until the number of lines of R code reaches the limit set by the maxlines() option (see below).
The user may specify a terminator() option and/or a using file qualifier,
both of which will be assumed to contain lines of R code for the R program to be run.
If the user specifies both a terminator() string and a using file qualifier,
then the inline R code will be placed before the R code from the file.

maxlines(#) specifies the maximum number of lines allowed
in the inline R code terminated by the terminator() string.
In default, maxlines(1024) is assumed.

noloutput specifies that the output from the R source code is not listed
to the Stata Results window and/or the Stata log file.
If noloutput is not specified,
then the output from the R source code is listed.

lsource specifies that the R source code is listed
to the Stata Results window and/or the Stata log file.
If lsource() is specified and noloutput is not specified,
then the R source file is listed before the output from the R command.

rpath(R_pathname) specifies a path name for invoking the R command.
If rpath() is not specified,
then it is set to the value of the global macro Rterm_path,
if that macro has been specified,
and to "Rterm.exe" otherwise.
(See Technical note below.)

roptions(R_options) specifies a set of options for the R command.
If roptions() is not specified,
then it is set to the value of the global macro Rterm_options,
if that macro has been specified,
and to the empty string "" otherwise.
(See Technical note below.)

Remarks

The R statistical software system can be downloaded from the R Project Website.
It is complementary to Stata in its capabilities, as it contains implementations of many methods unavailable in Stata,
but does not have as many easy-to-use data management tools as Stata.
It may therefore be useful to be able to call R in batch mode from within a Stata do-file.

R can read Stata dataset files using the read.dta and write.dta modules of the foreign package.
Alternatively, it is possible to translate between Stata and R datasets using Stat/Transfer,
which can be accessed from within Stata using the stcmd package, downloadable from SSC.
More recent R packages for exchange of data between Stata and R include haven and readstata13.
For more about import and export of data to and from R, refer to R Data Import/Export
(see References)
Note that packages for import of data to R from Stata may be added at any time.
Note, also, that new Stata versions may also be released,
which may or may not disable these R packages.

For more about the use of R for Stata users,
see Muenchen and Hilbe (2010).

Technical note

rsource works by running the Rterm.exe program of R.
The assumed R program path is displayed by rsource before any other output,
and is the assumed name and address of the R program run by rsource.
If the user does not specify the rpath() and roptions() options,
then rsource sets defaults.
In the case of rpath(), the default is the value of the global macro Rterm_path,
if that macro has been specified,
and otherwise is "Rterm.exe" if the operating system is Windows and "/usr/bin/r" otherwise.
In the case of roptions(), the default is the value of the global macro Rterm_options,
if that macro has been specified,
and is the empty string "" otherwise.
Therefore, the user should either set the system default file search path to include the directory containing the current version of R,
or set the global macros Rterm_path and Rterm_options to sensible default values before using rsource.

The setting of default values for Rterm_path and Rterm_options
is probably done most easily by inserting two lines into the user's Stata profile do-file
to initialize these global macros every time the user starts Stata.
For instance, under Windows, if the user's profile do-file contains the lines

. global Rterm_path `"c:\r\R-2.5.0\bin\Rterm.exe"'

. global Rterm_options `"--vanilla"'

and the Rterm.exe program of R, in the user's system, has path c:\r\R-2.5.0\bin\Rterm.exe,
then the user does not need to specify the rpath() and roptions() options of rsource,
because the R path is then set to its correct value,
and the R options are set to the sensible default value --vanilla.
Other possible R options, which can be set using roptions(),
are listed in Appendix B of An Introduction to R
(see References).

Note that, when the user downloads a new version of R, the installation process creates a new directory,
containing the new version of Rterm.exe.
Therefore, when R is upgraded,
the user should either change the system default file search path,
or change the line of code in the profile do-file setting the global macro Rterm_path.

Examples

. rsource using nitz2.R

. rsource using nitz2.R, lsource

. rsource using nitz2.R, noloutput roptions(--slave)

The following example illustrates the use of the terminator() option
to run an R program embedded inside a Stata program.
We use Stata to write the auto dataset to a file myauto.dta.
We then use rsource to run an instream R program,
which uses the module read.dta of the R package foreign
to read myauto.dta into a data frame in R,
and then lists this data frame and its attributes.
The module read.dta inputs a Stata dataset from a file
and outputs it to an R data frame,
with attributes that can be listed using the attributes() command in R.
The use of saveold to write the dataset myauto.dta
is probably a sensible precaution,
because the user's version of the R package foreign
may not be able to read Stata datafiles produced by the latest version of Stata.
Note that, in Stata Version 14,
the saveold command in this example should have the added option version(12).

. sysuse auto, clear

. describe, full

. saveold myauto.dta, replace

. rsource, terminator(END_OF_R)

. library(foreign);

. rauto<-read.dta("myauto.dta", convert.f=TRUE);

. rauto;

. attributes(rauto);

. q();

. END_OF_R

The following example does the same things as the previous example,
using the outputst module of the SSC package stcmd
to call Stat/Transfer
to output the auto dataset to an R workspace file myauto.dta,
which is then input to R using rsource.
The present author has been advised that Stat/Transfer
is now the officially approved tool
for converting Stata datasets to R workspace files,
because, at the time of writing,
the module read.dta of the R library foreign
only reads Stata datasets in the formats of Stata versions 5-12,
and there is no promise from StataCorp that the saveold command in Stata
will continue to output datasets in Stata versions 5-12 formats
in Stata versions 15 or higher.
Note that, in Stata Version 14,
the saveold command in this example should have the added option version(12).

. sysuse auto, clear

. describe, full

. saveold myauto.dta, replace

. rsource, terminator(END_OF_R)

. library(foreign);

. rauto<-read.dta("myauto.dta", convert.f=TRUE);

. rauto;

. attributes(rauto);

. q();

. END_OF_R

The following advanced example demonstrates the use of the roptions() option of rsource
with the --args option of the R command
to pass Stata temporary filenames to R.
This practice enables the user to pass temporary R workspace files between Stata and R,
knowing that these temporary files will be deleted after the current Stata session,
or even after the end of execution of the current do-file,
if rsource is executed in a do-file.
This practice can also be generalized
to pass other Stata macro values to R,
apart from temporary filenames.
On the other hand, this practice seems, at present,
to require the user to have a high level of R programming knowledge.
This example is intended as a demonstration,
and only transfers the auto dataset to R,
and then transfers it back to Stata,
reporting the various changes that have been made by Stat/Transfer
in the course of transferring the dataset in both directions.
The present author is currently thinking about how to make the integration of R and Stata easier to use,
and will welcome any suggestions from other users.

. sysuse auto, clear

. describe, full

. tempfile tf1 tf2

. outputst r "`tf1'" /y

. rsource, terminator(END_OF_R) roptions(`" --vanilla --args "`tf1'" "`tf2'" "')

. trailargs<-commandArgs(trailingOnly=TRUE);

. trailargs;

. loaded<-load(trailargs[1]);

. loaded;

. loaded[1];

. .GlobalEnv[[loaded[1]]];

. myauto<-.GlobalEnv[[loaded[2]]];

. .GlobalEnv[[loaded[2]]]<-NULL;

. ls();

. myauto;

. attributes(myauto);

. save(myauto, file=trailargs[2]);

. END_OF_R

. clear

. inputst r "`tf2'"

. describe, full

. char list

Author

Roger Newson, Imperial College London, UK.

Email: r.newson@imperial.ac.uk

References

Muenchen R. A. and J. M. Hilbe.
R for Stata users.
New York, NY: Springer; 2010.

Venables W. N., D. M. Smith, and the R Development Core Team.
An Introduction to R.
Downloadable from
the R Project Website.

The R Development Core Team.
R Data Import/Export.
Downloadable from
the R Project Website.

Also see

Manual: [GSW] C.3 Executing commands every time Stata is started,
[GSM] C.1 Executing commands every time Stata is started,
[GSU] C.1 Executing commands every time Stata is started

On-line: help for profile, profilew, profilem, profileu

help for stcmd if installed