0

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%3A00%3A00&end_date=2021-11-24+00%3A00%3A00&campaign_id=1011l3888&convert_currency=USD&ref_conversion_metric_id%5B%5D=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%3A00%3A00&end_date=2021-11-24+00%3A00%3A00&campaign_id=1011l3888&convert_currency=USD&ref_conversion_metric_id%5B%5D=2"

I imagine there should be like a wild card where the variable would be in.

Thanks

2 Answers 2

1

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%3A00%3A00&end_date={todays_date}+00%3A00%3A00&campaign_id=1011l3888&convert_currency=USD&ref_conversion_metric_id%5B%5D=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%3A00%3A00&end_date="
URL_2 <- "+00%3A00%3A00&campaign_id=1011l3888&convert_currency=USD&ref_conversion_metric_id%5B%5D=2"

paste0(URL_1, todays_date, URL_2)
Sign up to request clarification or add additional context in comments.

6 Comments

this works, and I like that you can tell "hey here it is where it goes" but is there a way to do this without having to breaking the URL, just in one pass
@JuanLozano what do you mean in one pass? Like not having to put the variable in like that in the glue statement? Or not having to split the URL in the paste0? These are probably the two most simple ways to go about it.
not having to split the URL
If you want to use paste() like that then you would need to split it. The glue solution let's you do it without breaking up the URL by just substituting in the value.
This changed the question in order to answer it effectively answering a different question. The other answer did directly answer the question.
|
1

We may use str_replace

library(stringr)
str_replace(URL, "(?<=end_date\\=)\\d{4}-\\d{2}-\\d{2}", todays_date)

Comments

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.