Setting working directory through a function

user3540633 picture user3540633 · Apr 16, 2014 · Viewed 9.6k times · Source

I am new to R. I am facing trouble setting my working directory through a function. This is what I have tried:

myfunction<-function(directory)
   {
     setwd(paste(getwd(),("/directory"))

   }

When I run myfunction("name") It gives error:cannot change working directory.

Thanks in advance for help.

Answer

G. Grothendieck picture G. Grothendieck · Apr 16, 2014

Try this:

myfunction <- function(directory) setwd( file.path(getwd(), directory) )

or realizing that getwd() is the default so it need not be specified:

myfunction <- function(directory) setwd(directory)

or realizing that your function actually performs the same function as setwd this would work:

myfunction <- setwd