6

参考标题,我正在考虑如何将单词之间的空格转换为 %20 。

例如,

> y <- "I Love You"

怎么做y = I%20Love%20You

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

非常感谢。

4

4 回答 4

22

另一种选择是URLencode()

y <- "I love you"
URLencode(y)
[1] "I%20love%20you"
于 2012-06-20T09:32:18.400 回答
8

gsub()是一种选择:

R> gsub(pattern = " ", replacement = "%20", x = y)
[1] "I%20Love%20You"
于 2012-06-20T09:24:54.323 回答
2

curlEscape()包中的函数RCurl完成了工作。

library('RCurl')
y <- "I love you"
curlEscape(urls=y)
[1] "I%20love%20you"
于 2013-06-30T20:25:27.190 回答
1

我喜欢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()当然不仅仅是替换空格。

于 2020-05-28T16:28:58.840 回答