Hi I have an URL string but I need to replace a specific portion of the string to a variable
this is the code I have
todays_date <- as.character(Sys.Date())
URL <- "https://api.performancehorizon.com/reporting/export/export/click.csv?start_date=2021-11-23 00:00:00&end_date=2021-11-24 00:00:00&campaign_id=1011l3888&convert_currency=USD&ref_conversion_metric_id[]=2"
I would need to change the date where it says end_date
at this moment is 2021-11-23 to whatever value the variable todays_date is, in this case is the sysdate (11/24/2021) so the final string should be
"https://api.performancehorizon.com/reporting/export/export/click.csv?start_date=2021-11-23 00:00:00&end_date=2021-11-24 00:00:00&campaign_id=1011l3888&convert_currency=USD&ref_conversion_metric_id[]=2"
I imagine there should be like a wild card where the variable would be in.
Thanks
CodePudding user response:
The package glue
can be helpful in cases like this. Notice I added in {todays_date}
to your URL string.
todays_date <- as.character(Sys.Date())
URL <- "https://api.performancehorizon.com/reporting/export/export/click.csv?start_date=2021-11-23 00:00:00&end_date={todays_date} 00:00:00&campaign_id=1011l3888&convert_currency=USD&ref_conversion_metric_id[]=2"
library(glue)
glue(URL)
Or of course, you can simply break up the URL and paste
it back together.
URL_1 <- "https://api.performancehorizon.com/reporting/export/export/click.csv?start_date=2021-11-23 00:00:00&end_date="
URL_2 <- " 00:00:00&campaign_id=1011l3888&convert_currency=USD&ref_conversion_metric_id[]=2"
paste0(URL_1, todays_date, URL_2)
CodePudding user response:
We may use str_replace
library(stringr)
str_replace(URL, "(?<=end_date\\=)\\d{4}-\\d{2}-\\d{2}", todays_date)