我有一個有趣的資料,它是客戶資料輸入程序的一個函式。每次有更新時,資料輸入團隊只需在同一個 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
謝謝你。
uj5u.com熱心網友回復:
加倍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.
uj5u.com熱心網友回復:
你可以試試這個:
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.
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/383177.html
