How to Convert “space” into “ ” with R

后端 未结 4 1849
礼貌的吻别
礼貌的吻别 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 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.

提交回复
热议问题