0

I often use windows to copy and paste file paths into R scripts, which results in something like the following:

file = 'C:\this\is\a\test.tif'

However, this results in an error and I have to manually switch the path seperators from \ to /

>file = 'C:\this\is\a\test.tif'
Error: '\i' is an unrecognized escape in character string starting "'C:\this\i"

If I were using Python, I would simply use the following to format the path correctly:

file = r'C:\this\is\a\test.tif'

Is there a similar R method to Python's raw string r'' method to quickly format paths?

Borealis
  • 8,044
  • 17
  • 64
  • 112
  • Unfortunately R does not support raw strings. A workaround may be with `scan`: http://stackoverflow.com/a/11812540/ – Blue Magister Feb 27 '14 at 17:53
  • possible duplicate of [Raw text strings for file paths in R](http://stackoverflow.com/questions/8197027/raw-text-strings-for-file-paths-in-r) – eddi Feb 27 '14 at 21:27
  • You can use RStudio's snippet feature to make pasting Windows paths less painful. See https://stackoverflow.com/a/39989341/3827849 – Josh Gilfillan Aug 12 '17 at 11:10
  • @BlueMagister From R 4.0.0 raw strings are supported. See [Escaping backslash () in string or paths in R](https://stackoverflow.com/questions/14185287/escaping-backslash-in-string-or-paths-in-r/63078969#63078969) – Henrik Aug 11 '20 at 16:17

1 Answers1

2

The closest thing that I can think of to the raw string read when working from the R command line is to use the scan function:

> tmp <- scan(what='')
1: 'C:\this\is\a\test.tif'
2: 
Read 1 item
> tmp
[1] "C:\\this\\is\\a\\test.tif"
> 

or

> tmp <- scan(what='',n=1)
1: C:\this\is\a\test.tif
Read 1 item
> tmp
[1] "C:\\this\\is\\a\\test.tif"
> cat(tmp, '\n')
c:\this\is\a\test.tif 

The scan function will prompt for input from the console, you can type or paste what you want there and the printing of tmp in this case shows that the backslashes were interpreted literally (so print shows them doubled and cat shows them as is).

Greg Snow
  • 48,497
  • 6
  • 83
  • 110
  • It's all right in console.But how to input filepath in code editor? – Cobin Nov 11 '17 at 03:08
  • If working in a code editor, paste it as is, then use the find and replace functionality of the editor. Or read it once using the console, then use the `dput` function to create a version to paste into the editor. – Greg Snow Nov 13 '17 at 19:46