Home > database >  Dynamically concatenating strings
Dynamically concatenating strings

Time:07-08

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

CodePudding user response:

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

  •  Tags:  
  • r
  • Related