5

Does anyone know of a simple way to return to the default working directory in R?

I know I can just type in my home path...

setwd("C:/Users/me/Desktop")

...but I guess I'm lazy. Is there a default command or something such as...

setwd(default)?

Thanks if you know the answer to this.

Paul

  • 1
    There's no such thing as a "default working directory in R". The working directory is determined at startup and can vary based on several things. – Joshua Ulrich Nov 20 '13 at 21:49
  • Just create a variable in your .Rprofile like: `myoriginalwd <- getwd()`. – Thomas Nov 20 '13 at 22:02
  • @Thomas: that still will vary based on how R is invoked, which doesn't seem to be what the OP wants. – Joshua Ulrich Nov 20 '13 at 22:03
  • @JoshuaUlrich Ah, I suppose, I was thinking of "default" as session-specific, but you're probably right that that's not the intention. – Thomas Nov 21 '13 at 06:32
  • My answer at https://stackoverflow.com/a/66962964/5114585 & my quick video at https://youtu.be/hMjzO4bAi70 will help you set a permanent working directory [when not in projects] – Dr Nisha Arora Aug 08 '22 at 03:39

3 Answers3

7

Here is an alternative solution, since the Defaults package has been archived:

# Use `formals<-`, but note the comment in the examples of ?formals:
#
## You can overwrite the formal arguments of a function (though this is
## advanced, dangerous coding).
formals(setwd) <- alist(dir = "C:/Users/me/Desktop")

Or you could mask base::setwd() with something like:

setwd <- function(dir) {
  if (missing(dir) || is.null(dir) || dir == "") {
    dir <- "C:/Users/me/Desktop"
  }
  base::setwd(dir)
}

UPDATE: The Defaults package has been archived, so this solution only works if you download the package from the CRAN archive and build from source yourself.

You could use the Defaults package to set it to what you want. Then you could just call setwd().

library(Defaults)
setDefaults(setwd, dir="C:/Users/me/Desktop")
setwd()

See this answer if you want to put the above code in your .Rprofile.

Joshua Ulrich
  • 173,410
  • 32
  • 338
  • 418
  • If I try to install the package I get this: Warning in install.packages : package ‘Defaults’ is not available (for R version 3.3.3). Looking it on google I found out that Package ‘Defaults’ was removed from the CRAN repository. – Giacomo Aug 18 '17 at 15:33
1

when you log in to R, type getwd(), that is your default working directory

Santhosh
  • 1,771
  • 1
  • 15
  • 25
-2

use (PWD) in the termial ,hope you got what you want

Developer
  • 1
  • 1