Skip to content

setting new working directories

10 messages · Bill Shipley, Abhijit Dasgupta, Chuck Cleland +6 more

#
Hello, and Happy New Year.  My default working directory is getting very
cluttered.  I know that I should be using a different working directory for
each project (I work in Windows), but do not know how to go about creating
different ones and moving back and forth between them.  I have read Venables
& Ripley (Modern Applied Statistics with S-PLUS, 1994) but this seems out of
date with respect to this topic and have searched through the documentation
but cannot find a clear explanation for doing this.  Can someone point me to
the proper documentation for creating and using different working
directories from within Windows (please, no comments about switching to
UNIX...).
Thanks.

Bill Shipley
#
The basic command for this is setwd() (for "set working directory")

You can save your workspace after you use the setwd command, and this 
will create a .RData file in that directory. In windows you can click on 
the .RData directory to open R using that particular working directory. 
You can always check on the current working directory using getwd().

Another useful command in this context is save.image (see ?save.image 
for details)

Abhijit
Bill Shipley wrote:
#
Bill Shipley wrote:
RSiteSearch("working directory") is very helpful.  In particular, look
at the help pages for getwd() and setwd().

  
    
#
See ?getwd and ?setwd to set the working directory
See ?load and ?save to read the workspace.

Cheers,

Thierry

------------------------------------------------------------------------
----

ir. Thierry Onkelinx

Instituut voor natuur- en bosonderzoek / Reseach Institute for Nature
and Forest

Cel biometrie, methodologie en kwaliteitszorg / Section biometrics,
methodology and quality assurance

Gaverstraat 4

9500 Geraardsbergen

Belgium

tel. + 32 54/436 185

Thierry.Onkelinx op inbo.be

www.inbo.be 

 

Do not put your faith in what statistics say until you have carefully
considered what they do not say.  ~William W. Watt

A statistical analysis, properly conducted, is a delicate dissection of
uncertainties, a surgery of suppositions. ~M.J.Moroney


-----Oorspronkelijk bericht-----
Van: r-help-bounces op stat.math.ethz.ch
[mailto:r-help-bounces op stat.math.ethz.ch] Namens Bill Shipley
Verzonden: donderdag 4 januari 2007 15:42
Aan: R help list
Onderwerp: [R] setting new working directories

Hello, and Happy New Year.  My default working directory is getting very
cluttered.  I know that I should be using a different working directory
for
each project (I work in Windows), but do not know how to go about
creating
different ones and moving back and forth between them.  I have read
Venables
& Ripley (Modern Applied Statistics with S-PLUS, 1994) but this seems
out of
date with respect to this topic and have searched through the
documentation
but cannot find a clear explanation for doing this.  Can someone point
me to
the proper documentation for creating and using different working
directories from within Windows (please, no comments about switching to
UNIX...).
Thanks.

Bill Shipley

______________________________________________
R-help op stat.math.ethz.ch mailing list
https://stat.ethz.ch/mailman/listinfo/r-help
PLEASE do read the posting guide
http://www.R-project.org/posting-guide.html
and provide commented, minimal, self-contained, reproducible code.
#
Bill,

I like to use Windows Explorer to find folders and then launch R with the 
selected folder as the working directory.

I put some notes online about this:
http://research.stowers-institute.org/efg/R/TechNote/WindowsExplorerWorkingDirectory/index.htm

efg

"Bill Shipley" <bill.shipley at usherbrooke.ca> wrote in message 
news:001001c7300e$7016b440$bb1ad284 at BIO041...
#
On 1/4/2007 9:41 AM, Bill Shipley wrote:
I don't think R has facilities for creating directories:  you would do 
that in the OS, e.g. in Windows Explorer, right click and ask for "New | 
Folder".

In Windows the easiest way to set a directory as the current working 
directory is

setwd(choose.dir())

In the choose.dir dialog you can type the directory name in standard 
Windows format (don't worry about escaping \), or you can use the 
directory browser to choose it.

By the way, if you do decide to switch to Unix, you'll have to do 
without choose.dir() (unless it's in a contributed package somewhere).

Duncan Murdoch
#
If you are working on Windows XP then downlaod the batchfiles
distribution whose home page is at:

http://code.google.com/p/batchfiles/

This will provide a bunch of batch files that are useful in connection
with using R.

At the Windows console this command shows you your path

   path

so place Rgui.bat from the batchfiles distribution in any of
the folders listed in the path or in the folder you want to be
your working directory.  Then issue this command at the
Windows console:

  Rgui.bat

That will start up R with the working directory set to the current
directory.

It also automatically finds which version of R you are using from the
registry so you don't have to do anything each time you install
a new version of R (unlike other methods).
On 1/4/07, Bill Shipley <bill.shipley at usherbrooke.ca> wrote:
#
On 1/4/2007 12:48 PM, Duncan Murdoch wrote:
A couple of people have pointed out dir.create() to me.  I would have 
found it with

help.search('directory')

Duncan Murdoch
#
Folks:

Motivated by the recent thread on setting working directories, below are a
couple of functions for GUI-izing saving and loading files **in Windows
only** that sort of takes care of this automatically.  The simple strategy
is just to maintain a file consisting of the filenames of recently saved
workspace (.Rdata, etc.)files. Whenever I save a workspace via the function
mySave() below, the filename is chosen via a standard Windows file browser,
and the filename where the workspace was saved is added to the list if it
isn't already there. The recent() function then reads this file and brings
up a GUI standard Windows list box (via select.list()) of the first k
filenames (default k = 10) to load into the workspace **and** sets the
working directory to that of the first file loaded (several can be brought
in at once).

I offer these functions with some trepidation: they are extremely simple and
unsophisticated, and you definitely use them at your own risk. There is no
checking nor warning for whether object names in one loaded file duplicate
and hence overwrite those in another when more than one is loaded, for
example. Nevertheless, I have found the functions handy, as I use the
"recently used files" options on all my software all the time and wanted to
emulate this for R.

Suggestions for improvement (or better yet, code!) or information about bugs
or other stupidities gratefully appreciated.

Cheers,

Bert Gunter
Genentech Nonclinical Statistics
South San Francisco, CA 94404


#### Code Follows  #####

mySave<-
function(recentlistFile=paste("c:/Program
Files/R","recentFiles.txt",sep="/"),
		savePlots=FALSE)
{
## DESCRIPTION:
## Use a windows GUI to save current workspace

## ARGUMENTS:
##    recentlistFile: a quoted character string giving the full
pathname/filename to
##		the file containing the listof recent files.
##		This must be the same as the "filename" argument of recent()
##    The default saves the file in the global R program directory, which
means it does not
##    have to be changed when updating to new versions of R which I store
under
##    the global R directory. You may need to change this if you have a
different
##    way of doing things.
##
##
##    savePlots: logical. Should the .SavedPlots plot history be saved? This
object can
##    be quite large and not saving it often makes saving and loading much
faster,
##    as well as avoiding memory problems. The default is not to save.

if(!savePlots) if(exists(".SavedPlots",where=1))rm(.SavedPlots,pos=1)

fname<-choose.files(caption='Save
As...',filters=Filters['RData',],multi=FALSE)
if(fname!=""){
	save.image(fname)
  if(!file.exists(recentlistFile))write(fname,recentlistFile,ncol=1)
  else{
	      nm<-scan(recentlistFile,what="",quiet=TRUE,sep="\n")
##      remove duplicate filenames and list in LIFO order
	      write(unique(c(fname,nm)),recentlistFile,ncol=1)
        }
	}
	else cat('\nWorkspace not saved\n')
}



 recent<-
function(filename=paste("c:/Program
Files/R","recentFiles.txt",sep="/"),nshow=10,
	setwork=TRUE)
{

## DESCRIPTION:
## GUI-izes workspace loading by bringing up a select box of files
containing
##	recently saved workspaces to load into R.

## ARGUMENTS:
        ## file: character. The full path name to the file containing the
file list, 
        ## which is a text file with the filenames, one per line.
        ##
        ##
        ## nshow: The maximum number of paths to show in the list
        ##
        ## setwork: logical. Should the working directory be set to that of
the first file
        ##  loaded?
        
        ## find the file containing the filenames if it exists
        if(!file.exists(filename))
                stop("File containing recent files list cannot be found.")
        filelist<-scan(filename,what=character(),quiet=TRUE,sep='\n')
        len<-length(filelist)
        if(!len)stop("No recent files")
        recentFiles<-select.list(filelist[1:min(nshow,len)],multiple=TRUE)
        if(!length(recentFiles))stop("No files selected")
        i<-0
        for(nm in recentFiles){
                if(file.exists(nm)){
                        load(nm,env=.GlobalEnv)
                        i<-i+1
                        if(i==1 &&setwork)setwd(dirname(nm))
                }
                else cat('\nFile',nm,'not found.\n')
        }
        cat('\n\n',i,paste(' file',ifelse(i==1,'','s'),' loaded\n',sep=""))
}
#
Bill Shipley wrote:
I'm not sure to which New Year you refer, but thanks and the same to you.

I think you may want to automatically start up R in a directory for each 
project. There is a discussion of that in Kickstarting R at:

http://cran.r-project.org/doc/contrib/Lemon-kickstart/kr_start.html

Basically, you can create icons on the desktop that will start R in a 
number of directories. In Windows, don't worry about adding the line to 
your "R" startup file, just set the "Start Program in" to the desired 
directory in the Properties dialog of the shortcut.

You can also set up an R file that gives you an interactive choice when 
the program starts. Create a file like this:

cat("R programming\n")
cat("Animals\n")
cat("Vegetables\n")
cat("Minerals\n")
cat("Type in the first letter of the project -")
answer<-toupper(strsplit(readline(""))[1])
if(answer == "R") setwd("c:/jim/R/programs")
if(answer == "A") setwd("c:/jim/things/animals")
...

and say you name it c:\jim\R\SelectProject.R
(notice that Windows uses backslashes but you use slashes in R)

put the following line in your .First function:

source("c:/jim/R/SelectProject.R")

and you should be able to select your project and directory on startup.

Jim