如何用R将“空格”转换为“%20”

时间:2012-06-20 09:21:50

标签: r curl rcurl

参考标题,我想知道如何将单词之间的空格转换为%20。

例如,

> y <- "I Love You"

如何制作y = I%20Love%20You

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

非常感谢。

4 个答案:

答案 0 :(得分:19)

另一种选择是URLencode()

y <- "I love you"
URLencode(y)
[1] "I%20love%20you"

答案 1 :(得分:8)

gsub()是一个选项:

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

答案 2 :(得分:1)

curlEscape()中的函数RCurl可以完成工作。

library('RCurl')
y <- "I love you"
curlEscape(urls=y)
[1] "I%20love%20you"

答案 3 :(得分:1)

我喜欢URLencode(),但要注意,有时候,如果您的网址中已经包含%20和一个实际的空格,则它可能无法按预期工作,在这种情况下,甚至repeated选项都不会URLencode()中的人正在做您想要的事情。

就我而言,我需要连续运行URLencode()gsub才能获得所需的确切信息,例如:

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"

在这个特定示例中,仅使用gsub()就足够了,但是URLencode()当然要做的不仅仅是替换空格。

相关问题