将日期作为因子错误地转换为日期

将日期作为因子错误地转换为日期

本文介绍了将日期作为因子错误地转换为日期的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我无法计算从.csv文件导入的日期。我要执行的操作是在DateClosed因子中获取该日期,并在日期字段(a)中生成一个日期。例如,如果a = 203,我希望日期等于DateClosed-203。但是,我在下面列出的代码上遇到了麻烦。

I am having trouble calculating a date that is imported in from a .csv file. What I want to do is take that date in the factor DateClosed and generate a date in a date field (a). Example if a=203 I want the date to be the equivalent of DateClosed-203. However, I am having trouble with the code listed below.

DateClose是一个因素。

DateClose is a factor.

> head(DateClosed)
[1] 7/30/2007  12/12/2007 5/8/2009   6/24/2009  6/24/2009  2/29/2008
165 Levels: 1/12/2010 1/15/2011 1/15/2013 1/17/2009 1/18/2008 1/19/2012 1/2/2013 1/21/2013 1/22/2010 1/24/2013 1/26/2014 ... 9/7/2010
> head(as.Date(DateClosed,format="%m/%d/%y"))
[1] "2020-07-30" "2020-12-12" "2020-05-08" "2020-06-24" "2020-06-24" "2020-02-29"

 head(as.Date(DateClosed,format="%m/%d/%y"))-203
[1] "2020-01-09" "2020-05-23" "2019-10-18" "2019-12-04" "2019-12-04" "2019-08-10"

它可以正确减去203天,但由于某种原因而误读了日期。

It subtracts 203 days correctly but for some reason reads the date wrong.

推荐答案

DateClosed <- factor(c("7/30/2007","12/12/2007", "5/8/2009"))
as.Date(DateClosed, format="%m/%d/%Y")

产生:

[1] "2007-07-30" "2007-12-12" "2009-05-08"

格式参数的大写字母 Y。小写的 y表示2位数字的年份,因此 as.Date 读取年令牌的前两位数字( 20),然后假定该数字表示仅是年份的最后两位数字,并加上当前日期的世纪(也为 20),因此您的日期以2020结尾。

Notice the capital "Y" in the format param. The lower case "y" is for 2 digit years, so as.Date reads the first two digits of the year token ("20"), and then assumes that refers to just the last two digits of the year, and adds the current date's century (also "20"), so you end up with dates in 2020.

这篇关于将日期作为因子错误地转换为日期的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-29 05:25