6

Referring the title, I'm figuring how to convert space between words to be %20 .

For example,

> y <- "I Love You"

How to make y = I%20Love%20You

> y
[1] "I%20Love%20You"

Thanks a lot.

4 Answers 4

22

Another option would be URLencode():

y <- "I love you"
URLencode(y)
[1] "I%20love%20you"
3
  • +1 Better than my Answer and a good reminder of this function's existance Jun 20, 2012 at 10:21
  • Important to note that this only replaces " " with %20, if you need to convert others, RCurl::curlEscape() is better.
    – Amit Kohli
    Aug 26, 2020 at 20:54
  • 1
    @AmitKohli if you need to convert other characters (such as !$&'()*+,;=:/?@#[] ) you can also use URLencode with argument reserved set to TRUE.
    – plannapus
    Aug 27, 2020 at 9:31
8

gsub() is one option:

R> gsub(pattern = " ", replacement = "%20", x = y)
[1] "I%20Love%20You"
2

The function curlEscape() from the package RCurl gets the job done.

library('RCurl')
y <- "I love you"
curlEscape(urls=y)
[1] "I%20love%20you"
1
  • Note that this will change "test!: " to "test%21%3A%20" vs URLencode "test!%3a%20" Feb 3, 2014 at 15:28
1

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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.