在R中的最后一个日期之后提取文本
Posted
技术标签:
【中文标题】在R中的最后一个日期之后提取文本【英文标题】:Extract text after the last date in 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
谢谢。
【问题讨论】:
【参考方案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, "\\d1,2/\\d2/\\d4")
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.
【讨论】:
以上是关于在R中的最后一个日期之后提取文本的主要内容,如果未能解决你的问题,请参考以下文章
excel中的日期时间读入R中为何会变成数字,如果我只想提取里面的年月日该用啥函数?