How to fix Windows path to use it in R

converting Windows path backslashes to slashes in R

In R, you cant use Windows file or folder path straight forward. The direction of the slash symbols is critical, and here is how to quickly fix the Windows path to use it in R.

I copied a path to my file that I would like to read and load in R.


After assigning it to a variable all I get is an error.

my_path <- "C:\MyFolder\Documents\R\ImportantFile.csv"

#Error: '\M' is an unrecognized escape in character string starting ""C:\M"

In R path should contain single forward slashes or double backslashes instead of single backslashes. A single backslash is considered an escape character.

The best way to get the file path in the correct form in R is with the function readClipboard(). It will automatically change a single backslash to a double backslash.


#[1] "C:\\MyFolder\\Documents\\R\\ImportantFile.csv"

Backslashes need to be doubled because a single one is the escape character in R. In other words, a single backslash in an R requires two backslashes.

If you fix the path in R and get a cleaner result, you can use gsub to replace backslashes with a forward slash like this.

gsub("\\\\", "/", readClipboard())

#[1] "C:/MyFolder/Documents/R/ImportantFile.csv"

Here are a couple of examples to remove unwanted characters in R. Characters like tab, line breaks, or carriage returns.

It is interesting that you can access Windows clipboard history with a shortcut. Here are how to do that and other useful Windows shortcuts.

0 comments on “How to fix Windows path to use it in R

Leave a Reply

Your email address will not be published. Required fields are marked *