【问题标题】:Extract text after the last date in R在R中的最后一个日期之后提取文本
【发布时间】:2022-01-18 23:21:48
【问题描述】:

我有一个有趣的数据,它是客户数据输入过程的函数。每次有更新时,数据输入团队只需将日期和相关 cmets 附加到同一个 Excel 单元格中。因此它看起来像这样......

entry <- "9/10/2021 received request to order more beer. 9/15/2021 Beer arrived in old truck 10/09/2021 Sent notice to driver."

团队真正需要做的只有两件事,即提取第一个日期,以及带有相关文本的最后一个日期。

它需要在这样的数据框中。

First date | Last date   | note
-----------+-------------+----------------------
9/10/2021  | 10/09/2021  | Sent notice to driver

谢谢。

【问题讨论】:

    标签: r string date text


    【解决方案1】:

    entry 加倍以显示此对字符串向量的作用:

    entry <- rep(entry, 2)
    

    基础 R 解决方案:

    gre <- gregexpr("[0-9]{1,2}/[0-9]{1,2}/[0-9]{2,4}.", entry)
    # fix the "match.length" to extend until the next match or EOS
    gre2 <- Map(function(G, txt) `attr<-`(G, "match.length", c(G[-1] - 1L, nchar(txt))), gre, entry)
    
    do.call(rbind, lapply(regmatches(entry, gre2), function(txt) {
      dat <- strcapture("([0-9]{1,2}/[0-9]{1,2}/[0-9]{2,4})\\s?(.*)", txt, list(date="", text=""))
      data.frame(first=dat$date[1],  last=dat$date[nrow(dat)], note=dat$text[nrow(dat)])
    }))
    #       first       last                   note
    # 1 9/10/2021 10/09/2021 Sent notice to driver.
    # 2 9/10/2021 10/09/2021 Sent notice to driver.
    

    【讨论】:

    • 经过一些测试,这与宣传的一样有效。再次感谢。
    • 太棒了!请accept回答。
    【解决方案2】:

    你可以试试这个:

    library(stringr)
    library(dplyr)
    
    dates <- str_extract_all(entry, "\\d{1,2}/\\d{2}/\\d{4}")
    text <- strsplit(entry, split = "(?<=\\d) ", perl=TRUE)
    
    `First date` <- dates[[1]][1]
    `Last date` <- dates[[1]][3]
    note <- text[[1]][4]
    
    df <- tibble(
      `First date`,
      `Last date`,
      note
    )
    
    df
    
    # A tibble: 1 × 3
      `First date` `Last date` note                  
      <chr>        <chr>       <chr>                 
    1 9/10/2021    10/09/2021  Sent notice to driver.
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-07-08
      • 2023-03-25
      • 2021-05-05
      • 1970-01-01
      • 1970-01-01
      • 2023-02-23
      • 1970-01-01
      相关资源
      最近更新 更多