简体   繁体   中英

replace a specific part of a string with the value of a variable with R

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

We may use str_replace

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

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM