Alex Coppock
Alex Coppock

Reputation: 2252

Command for "Set working directory to source file location"

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

Upvotes: 13

Views: 13435

Answers (4)

Ricky McMaster
Ricky McMaster

Reputation: 4647

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.

Upvotes: 0

Ciro
Ciro

Reputation: 11

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.

Upvotes: 1

keberwein
keberwein

Reputation: 536

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

dir <- dirname(parent.frame(2)$ofile)
setwd(dir)

Upvotes: 0

Romain
Romain

Reputation: 859

You can use :

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

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

Upvotes: 2

Related Questions