How to Convert “space” into “ ” with R

后端 未结 4 1800
礼貌的吻别
礼貌的吻别 2021-01-18 16:18

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

For example,

> y <- \"I Love You\"

How to

相关标签:
4条回答
  • 2021-01-18 16:51

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

    library('RCurl')
    y <- "I love you"
    curlEscape(urls=y)
    [1] "I%20love%20you"
    
    0 讨论(0)
  • 2021-01-18 17:03

    gsub() is one option:

    R> gsub(pattern = " ", replacement = "%20", x = y)
    [1] "I%20Love%20You"
    
    0 讨论(0)
  • 2021-01-18 17:03

    Another option would be URLencode():

    y <- "I love you"
    URLencode(y)
    [1] "I%20love%20you"
    
    0 讨论(0)
  • 2021-01-18 17:08

    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.

    0 讨论(0)
提交回复
热议问题