参考标题,我想知道如何将单词之间的空格转换为%20。
例如,
> y <- "I Love You"
如何制作y = I%20Love%20You
> y
[1] "I%20Love%20You"
非常感谢。
gsub()
是一种选择:
R> gsub(pattern = " ", replacement = "%20", x = y)
[1] "I%20Love%20You"
另一个选项是URLencode()
:
y <- "I love you"
URLencode(y)
[1] "I%20love%20you"
来自软件包curlEscape()
的功能RCurl
完成工作。
library('RCurl')
y <- "I love you"
curlEscape(urls=y)
[1] "I%20love%20you"
[我喜欢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()
当然要做的不仅仅是替换空格。