Selena Gomez Selena Gomez - 1 month ago 6
R Question

How to escape the symbol of percentage '%' in r?

In an url, I am dealing with the special character '%' that I should pass as a string. The url contain some argumnents so I use

sprintf.
How to escape the symbol '%' in r ?

start <- 1
#%s is my variable
url<-(sprintf('https://www.amazon.com/s/ref=sr_pg_%s?rh=n%3A172282%2Cn%3A%21493964%2Cn%3A502394%2Cn%3A281052%2Cn%3A12556502011%2Cn%3A3017941&page=%s&ie=UTF8', start, start))



invalid format '%2Cn%3A'; use format %s for character objects

Answer

As the helpfile for sprintf states:

A wrapper for the C function sprintf, ...

Thus, you escape it in R the same way you do for C, using double precentage signs %% to produce one %, as per

How to escape sprintf() % marks so they wont be recognized as variables?

On your code, we produce a url presumably extracting the first page in this amazon.com search:

url<-(sprintf('https://www.amazon.com/s/ref=sr_pg_%s?rh=n%%3‌​A172282%%2Cn%%3A%%21‌​493964%%2Cn%%3A50239‌​4%%2Cn%%3A281052%%2C‌​n%%3A12556502011%%2C‌​n%%3A3017941&page=%s‌​&ie=UTF8', start, start))

produces

> url
[1] "https://www.amazon.com/s/ref=sr_pg_1?rh=n%3A172282%2Cn%3A%21493964%2Cn%3A502394%2Cn%3A281052%2Cn%3A12556502011%2Cn%3A3017941&page=1&ie=UTF8"