Every now and then some of us have to work on a campus terminal. And most of the time you want to take the code and data with you. So you do what every student does – you hook up your own usb-drive and change work directories in RStudio.
But as soon as you start copy-pasting your directory from the OS [win10] to
setwd()
the first thing you notice is that R-syntax doesn’t like the \backslash and throws an error.
Since \backslash is a special operator to suppress metacharacters or escape sequences, it can’t be escaped without a second backslash.
So if you want to feed your code multiple datasets from different directories, you correct every directory manually. And campus terminal directories tend to be annoyingly long, where you have to change about 10 \backslashes each.
Not anymore.
This little snippet lets you copy-paste and set any directory you like in a second.
backslashConverter <- function(x){
x <- readline()
gsub("\\\\", "/", x)
}
set.wd <- function(){
setwd(backslashConverter())
}
# execution
set.wd()
How it works:
- the function backslashConverter calls another function – readline() and saves your copied directory into the variable x.
- readline() converts every single \ (from your directory) into a double \\. This way R won’t throw an error anymore.
- gsub() matches every double \\ in the string x and replaces it with /.
(this one is a little confusing, because a double \\ should look like \\\\, because in R it’s still an operator, so you open and close it twice.) - set.wd() is now your own function for set a directory. It calls the backslashConverter() and sets a new directory without changing anything manually.