Unable to use setwd() to change directory from absolute to relative pathway

61 views Asked by At

I get 'cannot change working directory' when I try using setwd() to change my working directory from using an absolute pathway (from C:/examplename/Dropbox/Files) to a relative pathway (~/Dropbox/Files)

I am using code that works in a shared Dropbox, and has syntax that uses relative pathways such as:

setwd(paste0("~/Dropbox/Files/", site))

However, when I run this code on my computer, I get an error that the file pathway cannot be found. I think it's because my working directory looks like:

getwd()

however, when I go to change it, I get the following error:

> setwd("~/Dropbox/Files")
Error in setwd("~/Dropbox/Files") : cannot change working directory

I've checked that I use the correct spelling, and I have tried file.path

> setwd(file.path("~","Dropbox","Files"))
Error in setwd(file.path("~", "Dropbox", "Files")) : 
  cannot change working directory

I was curious if anyone has any idea why I can't change it? If it matters, the person who wrote the code used a mac and I have a PC.

1

There are 1 answers

0
Tripartio On

In my case, I work on different computers shared with files shared by Dropbox. It seems to be a similar setup as yours, except that you have different users. Here's a script I use for several projects:

# Initialize environment and load data --------------

run_location <- "work"  # work | laptop | tablet
dropbox_path <- switch(
  run_location,
  "work" = "C:/Dropbox/",
  "laptop" = "S:/Dropbox/",
  "tablet" = "C:/Dropbox/"
)
defaultRFolder <- paste0(dropbox_path, "Travail/R/para")

wd <- paste0(dropbox_path, "Travail/Research/project_path")
setwd(wd)

All I need to change is the value of run_location at the beginning, then the script works based on my location. Here's a modification that might work for you:

run_location <- "windows_user"  # mac_user | windows_user
dropbox_path <- switch(
  run_location,
  "mac_user" = "~/Dropbox/",
  "windows_user" = "C:/examplename/Dropbox/"
)

wd <- paste0(dropbox_path, "Files")
setwd(wd)

So, on your computer, you should set

run_location <- "windows_user"  # mac_user | windows_user

while your colleague should set

run_location <- "mac_user"  # mac_user | windows_user

on theirs. That's the only thing you would need to change for the files to work on your respective computers.