简体   繁体   English

R 将日期转换为错误格式(年份为 5 位数字)

[英]R converts dates into a wrong format (year to a 5 digit number)

I have loaded a txt dataset into R.我已经将一个 txt 数据集加载到 R 中。 A part of it can be seen below:它的一部分可以在下面看到:

date    rf
1   19620102 0.011
2   19620103 0.011
3   19620104 0.011
4   19620105 0.011
5   19620108 0.011

I have tried to convert the dates using the following code:我尝试使用以下代码转换日期:

df$date <- format(as.Date(df$date), "%Y-%m-%d")

This gives the following results, that are not what I wanted:这给出了以下结果,这不是我想要的:

date    rf
1   55688-01-06 0.011
2   55688-01-07 0.011
3   55688-01-08 0.011
4   55688-01-09 0.011
5   55688-01-12 0.011

I wanted to convert the dates into the format as seen below:我想将日期转换为如下所示的格式:

date    rf
1   1962-01-02 0.011
2   1962-01-03 0.011
3   1962-01-04 0.011
4   1962-01-05 0.011
5   1962-01-08 0.011

Does anyone know how I can get the results that I want?有谁知道我怎样才能得到我想要的结果?

This works这有效

as.Date("19620102", "%Y%m%d")
#> [1] "1962-01-02"

Created on 2021-02-06 by the reprex package (v0.3.0)代表 package (v0.3.0) 于 2021 年 2 月 6 日创建

So just do所以就这样做

as.Date(as.character(df$date), "%Y%m%d")

We could also use ymd from lubridate我们也可以使用来自ymdlubridate

library(lubridate)
ymd(19620102)
#[1] "1962-01-02"

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

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