【问题标题】:replace a specific part of a string with the value of a variable with R用 R 变量的值替换字符串的特定部分
【发布时间】:2022-01-03 04:57:27
【问题描述】:

您好,我有一个 URL 字符串,但我需要将字符串的特定部分替换为变量

这是我的代码

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"

我需要将此时显示 end_date 的日期更改为 2021-11-23 到变量 todays_date 的任何值,在这种情况下是 sysdate (11/24/2021) 所以最后的字符串应该是

"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"

我想变量所在的地方应该有一个通配符。

谢谢

【问题讨论】:

    标签: r string


    【解决方案1】:

    glue 包在这种情况下会很有帮助。请注意,我在您的 URL 字符串中添加了 {todays_date}

    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)
    

    当然,您也可以简单地将 URL 和paste 重新组合在一起。

    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)
    

    【讨论】:

    • 这行得通,我喜欢你可以说“嘿,这就是它的去向”,但有没有一种方法可以做到这一点而无需破坏 URL,只需一次完成
    • @JuanLozano 一次传球是什么意思?就像不必在glue 语句中那样放入变量?或者不必在paste0 中拆分 URL?这可能是最简单的两种方法。
    • 不必拆分网址
    • 如果你想像这样使用paste(),那么你需要拆分它。 glue 解决方案让您无需破坏 URL,只需替换值即可。
    • 这改变了问题,以便有效地回答不同的问题。另一个答案确实直接回答了这个问题。
    【解决方案2】:

    我们可能会使用str_replace

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-04-06
      • 2015-12-21
      • 1970-01-01
      • 1970-01-01
      • 2011-07-26
      • 2021-03-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多