1

I have this static text https://api.xxx.com/resource/xxx?api-key=xxx&format=json&limit=500. I want to concatenate this string with the other string &filters[city]=Mumbai&filters[polutant_id]=PM10. The second string should be added dynamically based on the conditions shown in the list below.

cond=list(city=c("Mumbai,Delhi"), polutant_id=c("PM10,NO2"))

The output below contains 4 string as the above list has 4 possible combination of city and polutant_id.

Output

"https://api.xxx.com/resource/xxx?api-key=xxx&format=json&limit=500&filters[city]=Mumbai&filters[polutant_id]=PM10"

"https://api.xxx.com/resource/xxx?api-key=xxx&format=json&limit=500&filters[city]=Delhi&filters[polutant_id]=PM10"

"https://api.xxx.com/resource/xxx?api-key=xxx&format=json&limit=500&filters[city]=Mumbai&filters[polutant_id]=NO2"

"https://api.xxx.com/resource/xxx?api-key=xxx&format=json&limit=500&filters[city]=Delhi&filters[polutant_id]=NO2"

Note : There can be more or less than two elements in the list

1 Answer 1

3

in base R you can use sprintf to format the strings accordingly:

const <-"https://api.xxx.com/resource/xxx?api-key=xxx&format=json&limit=500"    
fmt <- '%s&filters[city]=%s&filters[polutant_id]=%s' #Note the placement of %s

You can then do:

do.call(sprintf, c(fmt, const, expand.grid(sapply(cond, strsplit,','))))


[1] "https://api.xxx.com/resource/xxx?api-key=xxx&format=json&limit=500&filters[city]=Mumbai&filters[polutant_id]=PM10"
[2] "https://api.xxx.com/resource/xxx?api-key=xxx&format=json&limit=500&filters[city]=Delhi&filters[polutant_id]=PM10" 
[3] "https://api.xxx.com/resource/xxx?api-key=xxx&format=json&limit=500&filters[city]=Mumbai&filters[polutant_id]=NO2" 
[4] "https://api.xxx.com/resource/xxx?api-key=xxx&format=json&limit=500&filters[city]=Delhi&filters[polutant_id]=NO2"  

Note that if you have a literal % in the format string fmt you will have to escape it by having double %%. learn more on sprintf

Sign up to request clarification or add additional context in comments.

2 Comments

Thanks a ton. Works like a charm. Is it possible to make it work even if there is more or less than two elements in the list. For e.g. if only city. Or 3 elements - city, state and pollutant_id?
@UjjawalBhandari you will have to dynamically create the fmt string. eg fmt <- paste0('%s', paste0('&filters[', names(cond), ']=%s', collapse = ''))

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.