as.Date 日期格式为 m/d/y in R [英] as.Date with dates in format m/d/y in R

查看:45
本文介绍了as.Date 日期格式为 m/d/y in R的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

一位客户向我发送了一个 Excel 文件,日期格式为 3 月 15 日的 3/15/2012.我将其保存为 .csv 文件,然后使用

A client sent me an Excel file with dates formatted as e.g 3/15/2012 for March 15. I saved this as a .csv file and then used

camm$Date <- as.Date(camm$Date, "%m/%d/%y")

但这给了我从 2020 年开始的价值!

but this gave me values starting in the year 2020!

我尝试重新格式化原始 csv 文件中的日期格式,例如2013 年 3 月 14 日,但无法这样做.

I tried to reformat the dates in the original csv file so that they were e.g. 03/14/2013 but was unable to do so.

感谢任何帮助

推荐答案

as.Date 调用中使用大写的 Y 代替.这应该可以解决问题:

Use capital Y in as.Date call instead. This should do the trick:

> as.Date("3/15/2012", "%m/%d/%Y")
[1] "2012-03-15"

从帮助文件的示例中您可以了解到,当指定年份已满时,您应该使用 %Y 否则使用 %y 例如:

From the help file's examples you can realize when year is full specified you should use %Y otherwise %y for example:

> dates <- c("02/27/92", "02/27/92", "01/14/92", "02/28/92", "02/01/92")
> as.Date(dates, "%m/%d/%y")
[1] "1992-02-27" "1992-02-27" "1992-01-14" "1992-02-28" "1992-02-01"

您可以看到,在您的示例中,年份格式为 2012,那么您应该使用 %Y,而在另一个示例中(取自 as.Date 帮助文件) 年份格式是 92 然后使用 %y 是正确的方法.有关详细信息,请参阅 as.Date.

You can see that in your example the Year format is 2012 then you should use %Y, and in the other example (taken from the as.Date help file) Year format is 92 then using %y is the correct way to go. See as.Date for further details.

这篇关于as.Date 日期格式为 m/d/y in R的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆