R:使用lubridate as.Dates函数将YYYYMMDD转换为日期 [英] R: Using the lubridate as.Dates function to convert YYYYMMDD to dates

查看:75
本文介绍了R:使用lubridate as.Dates函数将YYYYMMDD转换为日期的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当前,我正在尝试将YYYYMMDD格式的日期转换为年,月和日的单独列.我知道使用as.Date函数可以将YYYYMMDD转换为YYYY-MM-DD,然后从那里开始工作,但是R误解了日期,我不确定该怎么做.该功能正在将值转换为日期,但是转换不正确.

Currently I am attempting to convert dates in the YYYYMMDD format to separate columns for year, month, and day. I know that using the as.Date function I can convert YYYYMMDD to YYYY-MM-DD, and work from there, however R is misinterpreting the dates and I'm not sure what to do. The function is converting the values into dates, but not correctly.

例如:R将"19030106"转换为"2019-03-01",而应将其转换为"1903-01-06".我不确定如何解决此问题,但这是我正在使用的代码.

For example: R is converting '19030106' to '2019-03-01', when it should be '1903-01-06'. I'm not sure how to fix this, but this is the code I am using.

库(润滑)

PrecipAll $ Date<-as.Date(as.character(PrecipAll $ YYYYMMDD),format =%y%m%d")

YYYYMMDD当前为数字,我需要包含as.character以便完全输出日期,但是如果有更好的解决方案,请帮忙.

YYYYMMDD is currently numeric, and I needed to include as.character in order for it to output a date at all, but if there are better solutions please help.

此外,如果您有任何技巧将校正后的日期分为单独的Year,Month和Date列,将不胜感激.

Additionally, if you have any tips on separating the corrected dates into separate Year, Month, and Date columns that would be greatly appreciated.

推荐答案

使用{lubridate},尝试使用 ymd()解析YYYYMMDD变量,如果该变量是数字或字符形式,则不可变.还可以使用{lubridate}的 year month day 函数来获取这些变量作为数字信号.

With {lubridate}, try ymd() to parse the YYYYMMDD varaible, regradless if it is in numeric or character form. Also use {lubridate}'s year, month, and day functions to get those variables as numeric signals.

library(lubridate)

PrecipAll <- data.frame(YYYYMMDD = c(19030106, 19100207, 20001130))

mutate(.data = PrecipAll, 
       date = lubridate::ymd(YYYYMMDD), 
       year = year(date), 
       month_n = month(date), 
       day_n = day(date))

  YYYYMMDD       date year month_n day_n
1 19030106 1903-01-06 1903       1     6
2 19100207 1910-02-07 1910       2     7
3 20001130 2000-11-30 2000      11    30

这篇关于R:使用lubridate as.Dates函数将YYYYMMDD转换为日期的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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