Reputation: 41
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
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
source("https://raw.githubusercontent.com/imanojkumar/MyFunctions1/master/ChangeDirectory.R")
The above source file contains the below three codes:
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)
}
myfunction(directory)
Upvotes: 1
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
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