首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >将字符串的日期段转换为日期

将字符串的日期段转换为日期
EN

Stack Overflow用户
提问于 2020-10-24 08:50:47
回答 1查看 29关注 0票数 0

我有一个dataframe,其中有一列是导入的工作簿的文件名。工作簿的命名不是标准化的,但它们包含日期。我想从YYYY-MM-DD格式的所有字符串中提取日期,以便创建一个date列。

这是列外观的示例向量:

代码语言:javascript
复制
file_name <- c(
"Silly Elephant- September 30, 2011.xls",
"Silly Elephant- September 30, 2010.xls",
"NFL Las Vegas 10-31-16 Revised.xlsx",
"Silly Elephant July 31, 2011 (Revised).xls",
"Silly Elephant Report 1-31-2017.xlsx",
"Silly Elephant- September 30 2016.xlsx",
"Silly Elephant Report Feb 2020.xlsx",
"Silly Elephant Report 9-30-18.xlsx",                    
"Silly Elephant Report 9-30-2017.xlsx",                 
"Silly Elephant Report Apr 2019.xlsx",                  
"Silly Elephant Report Apr 2020.xlsx",                  
"Silly Elephant Report August 2019.xlsx",                
"Silly Elephant Report Dec 2018.xlsx",                  
"Silly Elephant Report December 2019.xlsx",              
"Silly Elephant Report FEB 2019.xlsx",                  
"Silly Elephant Report Feb 2020.xlsx",                   
"Silly Elephant Report Jan 2019.xlsx",                  
"Silly Elephant Report Jan 2020.xlsx",                   
"Silly Elephant Report July 2019.XLSX",                 
"Silly Elephant Report June 2019.xlsx",                  
"Silly Elephant Report Mar 2019.xlsx",                  
"Silly Elephant Report Mar 2020.xlsx",                   
"Silly Elephant Report May 2019.xlsx",                  
"Silly Elephant Report May 2020.xlsx",                   
"Silly Elephant Report November 2019.xlsx",
"Silly Elephant- June 30 2012.xlsx")
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2020-10-24 10:31:05

试试lubridateparse_date_time

代码语言:javascript
复制
as.Date(lubridate::parse_date_time(file_name, c('%B%d%Y', '%m-%d-%y')))

# [1] "2011-09-30" "2010-09-30" "2016-10-31" "2011-07-31"
# [5] "2017-01-31" "2016-09-30" "2020-02-20" "2018-09-30"
# [9] "2017-09-30" "2019-04-20" "2020-04-20" "2019-08-20"
#[13] "2018-12-20" "2019-12-20" "2019-02-20" "2020-02-20"
#[17] "2019-01-20" "2020-01-20" "2019-07-20" "2019-06-20"
#[21] "2019-03-20" "2020-03-20" "2019-05-20" "2020-05-20"
#[25] "2019-11-20" "2012-06-30"

如果您的向量采用其他格式的日期,您也可以添加它们。

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/64508938

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档