参考标题,我正在考虑如何将单词之间的空格转换为 %20 。
例如,
> y <- "I Love You"
怎么做y = I%20Love%20You
> y
[1] "I%20Love%20You"
非常感谢。
另一种选择是URLencode()
:
y <- "I love you"
URLencode(y)
[1] "I%20love%20you"
gsub()
是一种选择:
R> gsub(pattern = " ", replacement = "%20", x = y)
[1] "I%20Love%20You"
curlEscape()
包中的函数RCurl
完成了工作。
library('RCurl')
y <- "I love you"
curlEscape(urls=y)
[1] "I%20love%20you"
我喜欢URLencode()
,但请注意,如果您的 url 已经包含 a 和一个真实空间,有时它不会按预期工作%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()
当然不仅仅是替换空格。