Multiple-line path in R setwd()

It is not very common to have a long folder path in setwd() in R. However, when you do have a long working folder path and you would like to make several breaks while typing the path inside setwd(), it will be nice to have a simple way to do that.

The problem is after a line break, R automatically inserts a new line sign and several space immediately before the next path character. Here is an example.

R.version.string
## [1] "R version 3.6.3 (2020-02-29)"
# Create a long string with multiple breaks.
a = "C:/Users/My Documents/projects/My Data/Research/
    Project 1/Macroeconomics"
a
## [1] "C:/Users/My Documents/projects/My Data/Research/\n    Project 1/Macroeconomics"

After the line break, R inserts a new line sign and trailing white spaces. The objective will be to remove the the new line sign and the spaces so that we can have multiple line breaks and input a very long folder path. There are several solutions already discussed on stackoverflow.

Here we offer a solution without adding a user-defined function or using the paste function. It is similar to the one using gsub function but is robust to spaces in folder path such as "My Documents".

setwd(gsub("\\s{2,}|\n","","C:/Users/My Documents/projects/My Data/Research/
           Project 1/Macroeconomics"))

The code removes white space whenever it appears more than once in the path and also removes the new line sign. It helps preserve the necessary white space in phrases such as "My Documents".