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
  • 2,122
  • 3
  • 15
  • 31

4 Answers4

2

You can use :

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

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

hrbrmstr
  • 77,368
  • 11
  • 139
  • 205
Romain
  • 839
  • 10
  • 24
  • 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,624
  • 8
  • 31
  • 53
Ciro
  • 11
  • 1
  • > pathwd<-sub("/filename","",system("find -perm -g=w -type f -name 'filename'",intern=T)[1]) find: illegal option -- p usage: find [-H | -L | -P] [-EXdsx] [-f path] path ... [expression] find [-H | -L | -P] [-EXdsx] -f path [path ...] [expression] Warning message: running command 'find -perm -g=w -type f -name 'filename'' had status 1 – Alex Coppock Sep 23 '16 at 17:58
  • @AlexCoppock I would suggest that you might be using a Mac, and Ciro is on Linux. – Ricky McMaster Dec 07 '18 at 17:20
0

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

dir <- dirname(parent.frame(2)$ofile)
setwd(dir)
keberwein
  • 536
  • 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
  • 4,289
  • 2
  • 24
  • 23