12

RStudio has a useful feature:

Session -> Set Working Directory -> To Source File Location

Is there a way to do this without using the drop down menus?

UPDATE:

maybe a better way of asking is:

is there a command to return the file path of the current r script?

I also found this thread, but the solutions didn't work for me. Not even Hadley's!

Rscript: Determine path of the executing script

Community
  • 1
  • 1
Alex Coppock
  • 1,992
  • 3
  • 14
  • 29

4 Answers4

3

You can use :

source("script.R", chdir = TRUE)

and change "script.R" by the name of the file you're interested in.

hrbrmstr
  • 74,560
  • 11
  • 127
  • 189
Romain
  • 801
  • 8
  • 23
  • 3
    Thanks, this is close! But suppose I have started a new R file and saved it to a location. I then want to set the working directory to THAT file's location. I can't source the file without knowing the path -- which is the very problem we're trying to solve automatically. – Alex Coppock Oct 28 '14 at 22:02
  • R help said about 'chdir': if TRUE and file is a **pathname**, the R working directory is temporarily changed to the directory containing file for evaluating. – Faeze Jul 18 '16 at 13:07
1
pathwd<-sub("/filename","",system("find -perm -g=w -type f -name 'filename'",intern=T)[1])
setwd(pathwd)

Make sure your file's name is unique.

Yasin Patel
  • 5,276
  • 8
  • 30
  • 50
Ciro
  • 11
  • 1
0

This will work on most systems, it gets a little buggy with Macs.

dir <- dirname(parent.frame(2)$ofile)
setwd(dir)
keberwein
  • 511
  • 4
  • 8
0

Slight variation on @Ciro's answer above, for Mac users:

pathwd<-sub("/dummy.R","",system("find . -type f -name dummy.R",intern=T)[1]) 
setwd(pathwd)

Replace dummy.R with your filename of course.

Ricky McMaster
  • 3,767
  • 1
  • 23
  • 20