如何提取一列字符串的第二个日期?

问题描述 投票:0回答:2

我有一个包含日期字符串的数据框:

df <- tribble(
  ~text,
  "...text...1/5/17 ...text... 12/26/18",
  "...text...3/1/19 ...text... 4/5/19",
  "...text...10/5/14 ...text...",
  "...text...5/5/16 ...text... 9/16/17",
  "...text...",
  "...text...2/22/20 ...text..."
)

我想捕获每个字符串的第二个日期(如果存在)。最终我想将捕获的日期存储在数据框的一列中。我尝试使用

stringr::str_extract
并且即使使用
group=2
参数它似乎也没有捕获第二个日期。 (我很确定有更好的方法来编写正则表达式,但我真的想不出一个......)

str_extract(df$text, ".*(\\d+\\/\\d+\\/\\d+)|.*(\\d+\\/\\d+\\/\\d+)", group = 2)

输出

[1] NA NA NA NA NA NA

我的下一次尝试是使用

stringr::str_extract_all
。结果输出在
list
中,它捕获了第一个和第二个日期。我写了一个 for 循环来只提取每个字符串中的第二个日期。

str_extract_all(df$text, "(\\d+\\/\\d+\\/\\d+)") -> result

result2 <- rep(NA, length(result))

for (i in 1:length(result)){
  if(length(result[[i]] > 1)){
    result2[[i]] <- result[[i]][2]
  }
}

df$second_date <- result2
df

输出

> df
# A tibble: 6 × 2
  text                                 second_date
  <chr>                                <chr>      
1 ...text...1/5/17 ...text... 12/26/18 12/26/18   
2 ...text...3/1/19 ...text... 4/5/19   4/5/19     
3 ...text...10/5/14 ...text...         NA         
4 ...text...5/5/16 ...text... 9/16/17  9/16/17    
5 ...text...                           NA         
6 ...text...2/22/20 ...text...         NA  

我发现我所做的代码效率很低,想知道是否有其他方法可以完成相同的任务。如果可能的话,我想完全避免使用 for 循环。谢谢。

r regex stringr
2个回答
0
投票

这适用于示例数据 - 它找到在字符串末尾包含数字和斜杠的字符串:

library(stringr)
library(dplyr)
df <- tibble::tribble(
  ~text,
  "...text...1/5/17 ...text... 12/26/18",
  "...text...3/1/19 ...text... 4/5/19",
  "...text...10/5/14 ...text...",
  "...text...5/5/16 ...text... 9/16/17",
  "...text...",
  "...text...2/22/20 ...text..."
)
df %>% mutate(date = str_extract(text, "[\\d\\/]*$"), 
              date = lubridate::mdy(date))
#> # A tibble: 6 × 2
#>   text                                 date      
#>   <chr>                                <date>    
#> 1 ...text...1/5/17 ...text... 12/26/18 2018-12-26
#> 2 ...text...3/1/19 ...text... 4/5/19   2019-04-05
#> 3 ...text...10/5/14 ...text...         NA        
#> 4 ...text...5/5/16 ...text... 9/16/17  2017-09-16
#> 5 ...text...                           NA        
#> 6 ...text...2/22/20 ...text...         NA

创建于 2023-03-23 与 reprex v2.0.2


0
投票

您可以使用正则表达式来提取第二个日期。这个正则表达式抓取由数字和斜杠组成的字符串,位于字符串的末尾,并跟在

...text...

之后
second_date <- str_extract(df$text, '...text... ([0-9/]+$)',group = 1)
second_date
[1] "12/26/18" "4/5/19"   NA         "9/16/17"  NA         NA        

df$second_date <- second_date
df
# A tibble: 6 × 2
  text                                 second_date
  <chr>                                <chr>      
1 ...text...1/5/17 ...text... 12/26/18 12/26/18   
2 ...text...3/1/19 ...text... 4/5/19   4/5/19     
3 ...text...10/5/14 ...text...         NA         
4 ...text...5/5/16 ...text... 9/16/17  9/16/17    
5 ...text...                           NA         
6 ...text...2/22/20 ...text...         NA         
© www.soinside.com 2019 - 2024. All rights reserved.