You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何从含日期的字符串向量中筛选出对应最新日期的元素

从字符串向量中筛选包含最新日期的元素

可以通过提取日期、转换格式、匹配最大日期三个步骤实现,以下是具体R代码:

  1. 定义原始向量
vec <- c("The date is 1-2-23","Here it is 1-16-23",
"Here 2-16-23 is the latest", 
"4-3-23 is actually the latest","12-12-22 is the earliest")
  1. 提取字符串中的日期片段
    使用stringr包的str_extract函数,通过正则匹配提取所有数字-数字-数字格式的日期:
library(stringr)
date_strings <- str_extract(vec, "\\d+-\\d+-\\d+")
  1. 将日期字符串转换为可比较的日期对象
    使用lubridate包的mdy()函数(对应月-日-年的格式),把提取到的字符串转为日期类型:
library(lubridate)
date_objects <- mdy(date_strings)
  1. 筛选包含最新日期的原字符串
    用which.max()找到最大日期的索引,再从原始向量中提取对应元素:
Latest <- vec[which.max(date_objects)]

运行后Latest的值即为:

"4-3-23 is actually the latest"

内容的提问来源于stack exchange,提问作者user35131

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.25 03:32:39