4

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.

user3540633
  • 41
  • 1
  • 1
  • 2

3 Answers3

2

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
G. Grothendieck
  • 254,981
  • 17
  • 203
  • 341
1

I do not know but if you are interested, this may be helpful as well:

https://github.com/imanojkumar/MyFunctions1/blob/master/README.md

Or just use the below code:

source("https://raw.githubusercontent.com/imanojkumar/MyFunctions1/master/ChangeDirectory.R")

The above source file contains the below three codes:

1. Ask user to give path to directory

directory <-  readline('Enter Path to Directory You want to set as
                        Default (use backslash e.g. "E:/MyDirectory") : ')
2. Function
myfunction <- function(directory) {
if (!is.null(directory))
   setwd(directory)
}

3. Function runs in the background and sets the user defined directory as default

myfunction(directory)
Manoj Kumar
  • 5,273
  • 1
  • 26
  • 33
0

The issue you are facing is using "/directory". You will get the result if you just use directory instead of "directory"as in:

myfunction <- function(directory){
setwd(directory)
}

If you use the paste function, the output will be a character string and at the end it will be interpreted something like change my working directory to "directory" which does not exist and hence the error. R adds its own "" and hence your function becomes setwd(""directory"").You can read more in the help for path.expand()

Siddd
  • 274
  • 1
  • 3
  • 13