在R中转换日期格式

时间:2018-02-07 05:43:38

标签: r

head(df2)

           PointForecast     Lo 80    Hi 80      Lo 95    Hi 95   Region1
2017.0329       3.745038 0.8042195 6.685857 -0.7525558 8.242632 Ahmedabad
2017.0356       3.745038 0.7976683 6.692408 -0.7625749 8.252651 Ahmedabad
2017.0384       3.745038 0.7911317 6.698944 -0.7725718 8.262648 Ahmedabad
2017.0411       3.745038 0.7846095 6.705467 -0.7825467 8.272623 Ahmedabad
2017.0438       3.745038 0.7781017 6.711974 -0.7924996 8.282576 Ahmedabad
2017.0466       3.745038 0.7716080 6.718468 -0.8024307 8.292507 Ahmedabad

这里的rownames在我的df2中为2017.0356,............... 在这里,我需要将2017.0329,2017.0356,..............转换为年 - 月 - 日格式

请提出任何建议

1 个答案:

答案 0 :(得分:2)

希望这有帮助!

library(lubridate)

#I have added time as well because row names can't have duplicate values.
row.names(df2) <- format(date_decimal(as.numeric(row.names(df2))), "%Y-%m-%d %H:%m:%s")

输出是:

                            Forecast     Lo.80    Hi.80      Lo.95    Hi.95   Region1
2017-01-13 00:01:1484246534 3.745038 0.8042195 6.685857 -0.7525558 8.242632 Ahmedabad
2017-01-13 23:01:1484331681 3.745038 0.7976683 6.692408 -0.7625749 8.252651 Ahmedabad
2017-01-15 00:01:1484419982 3.745038 0.7911317 6.698944 -0.7725718 8.262648 Ahmedabad
2017-01-16 00:01:1484505129 3.745038 0.7846095 6.705467 -0.7825467 8.272623 Ahmedabad
2017-01-16 23:01:1484590276 3.745038 0.7781017 6.711974 -0.7924996 8.282576 Ahmedabad
2017-01-18 00:01:1484678577 3.745038 0.7716080 6.718468 -0.8024307 8.292507 Ahmedabad

示例数据:

df2 <- structure(list(Forecast = c(3.745038, 3.745038, 3.745038, 3.745038, 
3.745038, 3.745038), Lo.80 = c(0.8042195, 0.7976683, 0.7911317, 
0.7846095, 0.7781017, 0.771608), Hi.80 = c(6.685857, 6.692408, 
6.698944, 6.705467, 6.711974, 6.718468), Lo.95 = c(-0.7525558, 
-0.7625749, -0.7725718, -0.7825467, -0.7924996, -0.8024307), 
    Hi.95 = c(8.242632, 8.252651, 8.262648, 8.272623, 8.282576, 
    8.292507), Region1 = c("Ahmedabad", "Ahmedabad", "Ahmedabad", 
    "Ahmedabad", "Ahmedabad", "Ahmedabad")), .Names = c("Forecast", 
"Lo.80", "Hi.80", "Lo.95", "Hi.95", "Region1"), class = "data.frame", row.names = c("2017.0329", 
"2017.0356", "2017.0384", "2017.0411", "2017.0438", "2017.0466"
))