Trouble with setwd() in R

4.9k views Asked by At

My apologies if this has been answered already, I've looked through many very similar threads but haven't found a solution. I'm new to R, just started a few days ago but I feel like I'm making decent progress. I'm attempting to load in some old data from my undergrad thesis to mess around with a bit, but can't seem to get my working directory to change.

So far, I've created a path:

path<- file.path("C:", "Users", "Daniel", "Desktop",
                 "R_Practice", "Thesisdata.csv")

and I had success with reading the file designated by the path with

read.csv(path, stringsAsFactors = TRUE)

However, when I try to use

setwd(path)

or

setwd("C:", "Users", "Daniel", "Desktop",
      "R_Practice", "Thesisdata.csv")

I get an error message reading

Error in setwd(x) : cannot change working directory."

Can anybody explain to me what I'm doing wrong or point me in the right direction? I don't really understand why it would be able to successfully read the file using the path but can't set it to the working directory.

1

There are 1 answers

1
Ben Bolker On

Your problem is that you're confusing a directory (".../R_Practice") with a file (".../R_Practice/thesisdata.csv"). As @cory says in comments, you can't change the working directory to a file.

Try

path <- file.path("C:", "Users", "Daniel", "Desktop", "R_Practice")
setwd(path)
r <- read.csv("Thesisdata.csv")

Which should be equivalent to

r <- read.csv(file.path(path,"Thesisdata.csv"))

(except of course that the former approach leaves you in the appropriate working directory, so that you don't have to keep prepending the full path to your file names)

Furthermore, setwd() takes a single string: setwd("C:",...,"R_Practice") would never work in any case.