[R] Changing workspace from within an R session

gerald.jean@dgag.ca gerald.jean at dgag.ca
Tue Jan 20 16:51:36 CET 2004

Hello R-users,

is it possible to navigate from one workspace to the other from within an R
session or does one has to close R and restart it from the directory where
resides the desired workspace?

For example from Splus I have this little function, see at the end, which I
used all the time to navigate between valid Splus directories.  I find this
particularly usefull when I develop new functions.  Most projects I work on
are large to extremely large, developing a function that takes a data.frame
as input and manipulates it is very time consuming if the input data.frame
is huge hence I have a valid Splus directory holding a few small
data.frames, I move to it while developing the function and when I am happy
with the function I move this function to my personnal library, always
attached at position 2, then move back to the the current project's valid
Splus directory.

I tried a similar approach in R, from the command line --not using a
function yet, and I was a bit surprised by the result.  The objects already
in the workspace, as called in R, stayed there and the objects from the
workspace I wanted to attach were added to the current workspace and the
workspace I was hoping to attach at pos 1 was attach at pos 2 with
seemingly nothing in it?

> attach("/home/jeg002/splus/GlmExamples/.RData", pos = 1)
> search()
 [1] ".GlobalEnv"
 [2] "file:/home/jeg002/splus/GlmExamples/.RData"
 [3] "package:methods"

> objects(pos = 2)

The little function, mentioned above, and used in Splus.

"chdir" <-
function(datadir,  default.path = '/actuaria/jeg002/')
# Author  : Gerald Jean
# Date    : May 1999
# Purpose : "newdir" will be attached at position 1, and the S directory,
#           currently at position 1 will be detached.
# Arguments:
#  datadir      : the directory to attach.
#  default.path : the drive on which resides the directory to attach.
data.dir.to.detach <- search()[1]
to.attach <- paste(default.path, datadir, "/.Data", sep = "")
attach(to.attach, pos = 1)
detach(what = data.dir.to.detach)

Thanks for your insights,

Gérald Jean
Analyste-conseil (statistiques), Actuariat
télephone            : (418) 835-4900 poste (7639)
télecopieur          : (418) 835-6657
courrier électronique: gerald.jean at spgdag.ca

"In God we trust all others must bring data"  W. Edwards Deming

More information about the R-help mailing list