[R] how to run a script at the beginning of an interacive session ?

Marc Schwartz MSchwartz at mn.rr.com
Wed Jun 8 15:56:34 CEST 2005


On Tue, 2005-06-07 at 21:33 -0700, Mike R wrote:
> On 6/7/05, Marc Schwartz <MSchwartz at mn.rr.com> wrote:
> On 6/7/05, Gabor Grothendieck <ggrothendieck at gmail.com> wrote:
> On 6/7/05, Liaw, Andy <andy_liaw at merck.com> wrote:
> <snips>
> 
> Thanks Andy, Gabor and Marc.
> 
> 
> ---- contents of .Rprofile ----
> .First <- function() {source("startup.r")}
> 
> 
> ---- contents of wrapR.v1 ----
> #!/bin/bash
> ln -s $1 startup.r
> R
> rm -f startup.r
> 
> 
> ---- contents of wrapR.v2 ----
> #!/bin/bash
> echo ".First <- function() {source(\"$1\")}" > .Rprofile
> R
> 
> ---- contents of project_A.r ----
> library(graphics)
> plot(1:10)
> 
> 
> and then start R with either of the following command lines:
> ## ./wrapR.v1 project_A.r
> ## ./wrapR.v2 project_A.r
> 
> 
> What do you think? is this the most simple way?
> 
> Thanks in advance,
> 
> Mike

Mike,

There are several options here, and I would try to stay with a simple
approach, minimizing having to modify files, such as you are doing in
wrapR.v2, which BTW will overwrite all other contents of ~/.Rprofile.

You could get very complicated if you wanted and use something like
'sed' to engage in non-interactive editing of the ~./Rprofile file, but
I think that would increase the complexity beyond what is needed here.

One possible approach, subject to comment by others, would be to have
your normal default ~/.Rprofile file containing your base specifications
for a default startup.

Then, create one or more ~/.RprofileX files, where X is a number of 1:n,
for each separate file.

In each of these files, fully construct a .First function (as opposed to
sourcing() a separate file), such as:

# In file ~/.Rprofile1
...
.First <- function()
{
  library(graphics)
  plot(1:10)
}


# In file ~/.Rprofile2
...
.First <- function()
{
  library(graphics)
  barplot(1:10)
}


In each of the above, replace the '...' with the core contents of
~/.Rprofile so that besides .First, all else is the same if you want it
that way.


With the above in place, now run R from a terminal or within a shell
script using:

R_PROFILE=~/.Rprofile1 R --no-init-file


OR

R_PROFILE=~/.Rprofile2 R --no-init-file


In this way, by setting the R_PROFILE environment variable, you can
define which init file to use on startup. The use of "--no-init-file"
ignores your default ~/.Rprofile file to avoid any possible conflicts
there.

Note, importantly, this approach would obviate the use of any "site-
wide" .Rprofile file, which by default would be
$R_HOME/etc/Rprofile.site.

Now all you have to do is to create a new ~/.RprofileX each time you
want to utilize a different .First by modifying the command line call to
R.

If you want to run R with a default startup (ie. no .First function),
just use R as per normal. 

HTH,

Marc Schwartz




More information about the R-help mailing list