How to URL Encode a Backslash with R/RCurl

r, rcurl, urlencode

Solution

You are looking for

> URLencode("hello\\hello")
[1] "hello%5chello"

The error you're getting is not from any of the functions you tried to call; it didn't get as far as actually calling any of them. The error is from R's parser. Backslash is a special character for string literals themselves, so you need to write a double backslash in your string literal in order to produce a string value containing a backslash. (There are several other things you can usefully put after the backslash; for instance, `"\""` is how you write a string value consisting of one double-quote character. Read `?Quotes` for further information.)

Since this is an issue with the syntax of string literals, it shouldn't come up if you're reading the "string for insertion into a URL" from a data source; it should only be an issue if you need to write this string directly in your code.

Problem

I'm currently trying to encode a string for insertion into a URL. My issue is that this seems to fail when my string contains a backslash. I've tried 4 approaches so far using the URLencode, curlEscape (from RCurl), and curlPercentEncode (from RCurl) functions, but none of them have been successful. ``` > URLencode("hello\hello") Error: '\h' is an unrecognized escape in character string starting ""hello\h" > curlEscape("hello\hello") Error: '\h' is an unrecognized escape in character string starting ""hello\h" > curlPercentEncode("hello\hello") Error: '\h' is an unrecognized escape in character string starting ""hello\h" > curlPercentEncode("hello\hello", amp=TRUE) Error: '\h' is an unrecognized escape in character string starting ""hello\h" ```

Original source