Referring the title, I\'m figuring how to convert space between words to be %20 .
For example,
> y <- \"I Love You\"
How to
The function curlEscape()
from the package RCurl
gets the job done.
library('RCurl')
y <- "I love you"
curlEscape(urls=y)
[1] "I%20love%20you"
gsub()
is one option:
R> gsub(pattern = " ", replacement = "%20", x = y)
[1] "I%20Love%20You"
Another option would be URLencode()
:
y <- "I love you"
URLencode(y)
[1] "I%20love%20you"
I like URLencode()
but be aware that sometimes it does not work as expected if your url already contains a %20
together with a real space, in which case not even the repeated
option of URLencode()
is doing what you want.
In my case, I needed to run both URLencode()
and gsub
consecutively to get exactly what I needed, like so:
a = "already%20encoded%space/a real space.csv"
URLencode(a)
#returns: "encoded%20space/real space.csv"
#note the spaces that are not transformed
URLencode(a, repeated=TRUE)
#returns: "encoded%2520space/real%20space.csv"
#note the %2520 in the first part
gsub(" ", "%20", URLencode(a))
#returns: "encoded%20space/real%20space.csv"
In this particular example, gsub()
alone would have been enough, but URLencode()
is of course doing more than just replacing spaces.