user3540633
user3540633

Reputation: 41

Setting working directory through a function

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.

Upvotes: 4

Views: 10496

Answers (3)

Manoj Kumar
Manoj Kumar

Reputation: 5637

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)

Upvotes: 1

Siddd
Siddd

Reputation: 284

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()

Upvotes: 0

G. Grothendieck
G. Grothendieck

Reputation: 269526

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

Upvotes: 2

Related Questions