简体   繁体   English

为什么 R 中的 as.Date function 会将我输入的年份转换为当前年份 2020?

[英]Why does the as.Date function in R converts the years I enter into the current year 2020?

I have some dates in a dataframe, and when I use as.Date() to convert them into dates, the years convert into 2020, which isn't really valid because the file only has data up to 2018.我在 dataframe 中有一些日期,当我使用 as.Date() 将它们转换为日期时,年份转换为 2020 年,这实际上并不有效,因为该文件仅包含截至 2018 年的数据。

What I have so far:到目前为止我所拥有的:

> fechadeinsc1[2]
[1] "2020-08-15"

> class(fechadeinsc1)
[1] "Date"

> fechainsc[2]
[1] "2017/99/99"

> class(fechainsc)
[1] "character"

As you can see, fechadeinsc1 was converted into a date and fechainsc is the original dataframe which elements are characters.如您所见,fechadeinsc1 被转换为日期,而 fechainsc 是原始的 dataframe 其中元素是字符。 "fechadeinsc1" should give the same year, shouldn't it? “fechadeinsc1”应该是同一年,不是吗? Even though days and months aren't valid.即使日期和月份无效。

Another example :另一个例子

> fechadenac1[2]
[1] "2020-12-31"

> class(fechadenac1)
[1] "Date"

> fechanac[2]
[1] "12/31/2016"

> class(fechanac)
[1] "character"

Again, the year changes.又是一年的变化。

My code :我的代码

fechanac <- dat$fecha_nac
fechainsc <- dat$fecha_insc

fechadeinsc1 <- as.Date(fechainsc,tryFormats =c("%d/%m/%y","%m/%d/%y","%y","%d%m%y","%m%d%y"))
fechadenac1 <- as.Date(fechanac,tryFormats =c("%d/%m/%y","%m/%d/%y","%y","%d%m%y","%m%d%y"))

"dat" is the original dataframe which contains information about newborns registered in 2016 and 2017 in Ecuador, if anyone wants the original.csv file please contact me. “dat”是原始的dataframe,其中包含有关厄瓜多尔2016年和2017年注册的新生儿的信息,如果有人想要原始的.csv文件,请与我联系。

Based on strptime , referred from as.Date , you should use upper case Y for 4-digit years:基于strptime ,引用自as.Date ,您应该使用大写 Y 表示 4 位数年份:

%y Year without century (00--99). %y没有世纪的年份 (00--99)。 On input, values 00 to 68 are prefixed by 20 and 69 to 99 by 19 -- that is the behaviour specified by the 2004 and 2008 POSIX standards, but they do also say 'it is expected that in a future version the default century inferred from a 2-digit year will change'.在输入时,值 00 到 68 以 20 为前缀,69 到 99 以 19 为前缀——这是 2004 年和 2008 年 POSIX 标准指定的行为,但他们也说“预计在未来的版本中,默认世纪推断从 2 位数的年份将发生变化'。

%Y Year with century. %Y年份与世纪。 [...] [...]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM