简体   繁体   中英

Is it possible to define a cross-platform working directory for R?

I am teaching R tutorials in person w/ a large number of undergraduate R novices. I am also trying to format my notes on RPubs so that they can easily be used by other people. Nothing derails things faster than people mis-specifying working directories or saving spreadsheet files to someplace different than their working directory.

Is it possible to define a working directory that is universal across platforms? For example, a line of code or a function like

setwd( someplace that is likely to exist on every computer)

This could involve a function that finds some place the usually exists on all computers, such as the desktop, downloads folder, or R directory.

In general your best bet is to go for the user's home area,

setwd("~")
path.expand("~")

Since you are teaching novices, a common problem is that students notice the R package directory ~/R/ and assume that they should put their scripts this directory; thereby creating odd bugs. To avoid this, I would go for

dir.create("~/RCourse", FALSE)
setwd("~/RCourse")

If you use RStudio, you could get them to create an RStudio project.

In the past, I have come across situations where this doesn't work. For example, some people have their home area as a network drive, but can't connect to the internet or get through a firewall.

You asked about

someplace that is likely to exist on every computer

and yes, R works hard to ensure this returns a valid directory: tempdir() .

The main danger, though, may be that this directory will vanish after the session (unless you override the default behaviour of removing the per-session temporary directory at end). Until then, it works.

Still, this can be useful. I sometimes use that to write temporary files I don't want to clutter in the current directory, or ~ .

Otherwise @csgillespie gave you a good answer pertaining to $HOME aka ~ .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM