如何将混合日期格式的变量转换为一种格式?

编程入门 行业动态 更新时间:2024-10-10 00:29:20
本文介绍了如何将混合日期格式的变量转换为一种格式?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我的数据框示例:

date 1 25 February 1987 2 20 August 1974 3 9 October 1984 4 18 August 1992 5 19 September 1995 6 16-Oct-63 7 30-Sep-65 8 22 Jan 2008 9 13-11-1961 10 18 August 1987 11 15-Sep-70 12 5 October 1994 13 5 December 1984 14 03/23/87 15 30 August 1988 16 26-10-1993 17 22 August 1989 18 13-Sep-97

我有一个很大的数据框,其中的日期变量具有多种日期格式。变量中的大多数格式如上所示-还有一些非常罕见的其他格式。之所以存在多种格式,是因为数据是从各个使用不同格式的网站中收集的。

I have a large dataframe with a date variable that has multiple formats for dates. Most of the formats in the variable are shown above- there are a couple of very rare others too. The reason why there are multiple formats is that the data were pulled together from various websites that each used different formats.

我尝试使用简单的转换方法,例如

I have tried using straightforward conversions e.g.

strftime(mydf$date,"%d/%m/%Y")

,但是如果有多种格式,则这种转换将无法进行。我不想诉诸于多种gsub类型编辑。我想知道是否缺少更简单的解决方案?

but these sorts of conversion will not work if there are multiple formats. I don't want to resort to multiple gsub type editing. I was wondering if I am missing a more simple solution?

例如代码:

structure(list(date = structure(c(12L, 8L, 18L, 6L, 7L, 4L, 14L, 10L, 1L, 5L, 3L, 17L, 16L, 11L, 15L, 13L, 9L, 2L), .Label = c("13-11-1961", "13-Sep-97", "15-Sep-70", "16-Oct-63", "18 August 1987", "18 August 1992", "19 September 1995", "20 August 1974", "22 August 1989", "22 Jan 2008", "03/23/87", "25 February 1987", "26-10-1993", "30-Sep-65", "30 August 1988", "5 December 1984", "5 October 1994", "9 October 1984"), class = "factor")), .Names = "date", row.names = c(NA, -18L), class = "data.frame")

推荐答案

您可以在<$ c包中尝试 parse_date_time $ c> lubridate 使用 orders 参数允许用户指定几种格式顺序来处理不同的日期时间字符表示形式。像...

You may try parse_date_time in package lubridate which "allows the user to specify several format-orders to handle heterogeneous date-time character representations" using the orders argument. Something like...

library(lubridate) parse_date_time(x = df$date, orders = c("d m y", "d B Y", "m/d/y"), locale = "eng")

...应该能够处理大多数格式。请注意, b / B 格式对区域设置敏感。

...should be able to handle most of your formats. Please note that b/B formats are locale sensitive.

订单中可以使用的其他日期时间格式在的详细信息部分中列出了吗? strptime 。

Other date-time formats which can be used in orders are listed in the Details section in ?strptime.

更多推荐

如何将混合日期格式的变量转换为一种格式?

本文发布于:2023-05-25 19:52:49,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/236218.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:格式   转换为   变量   如何将   日期

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!