我有一个字符向量,如下表所示,我想从中提取日期并将它们转换为 as.Date
。例如,第一行是 09-11-2021。字符串中的最后一个数字是列数而不是日期的一部分。
<chr>
1 By Leigh-Ann Butler, Shannon Cobb, Michael R. DonaldsonNov 9, 20213 Comments
2 By Leigh-Ann Butler, Shannon Cobb, Michael R. DonaldsonNov 8, 20212 Comments
3 By Rick AndersonNov 4, 202114 Comments
4 By Victoria Ficarra, Rob JohnsonNov 3, 20215 Comments
5 By Roger C. SchonfeldNov 1, 202123 Comments
6 By Joseph EspositoOct 29, 20211 Comment
7 By Brigitte ShullOct 20, 20216 Comments
example.data <- c("By Leigh-Ann Butler, Shannon Cobb, Michael R. DonaldsonNov 9, 20213 Comments",
"By Leigh-Ann Butler, Shannon Cobb, Michael R. DonaldsonNov 8, 20212 Comments",
"By Rick AndersonNov 4, 202114 Comments",
"By Victoria Ficarra, Rob JohnsonNov 3, 20215 Comments")
最佳答案
你可以使用
as.Date(gsub(".+(\\w{3}\\s\\d{1,2},\\s\\d{4}).*", "\\1", example.data), format = "%b %d, %Y")
#> [1] "2021-11-09" "2021-11-08" "2021-11-04" "2021-11-03"
关于r - 从R中的字符串中提取混合日期,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/74931487/