简体   繁体   English

结合日、月、年、小时到R中的日期时间

[英]Combine day,month,year,hour to date time in R

day   month     year    hour
01     05      2017     00
05     12      2017     01
10     07      2017     23

i don't have column minute and seconds now i am trying to get a single variable as date_time in the format of我现在没有分和秒列 我正在尝试以以下格式获取单个变量作为 date_time

2017-05-01 00:00:00
2017-12-05 01:00:00
2017-07-10 23:00:00

getting the error while using the below code使用以下代码时出现错误

df$date <- as.Date(with(df, paste(year, month, day,hour,sep="-")),
           "%Y-%m-%d %H:%M:%S") 

thanks in advance提前致谢

We can try paste the columns together with sprintf , then convert to datetime with as.POSIXct 我们可以尝试将列与sprintf paste在一起,然后使用as.POSIXct转换为datetime。

as.POSIXct(do.call(sprintf, c(df1, fmt = c("%02d-%02d-%4d %02d"))), format = "%d-%m-%Y %H")
#[1] "2017-05-01 00:00:00 IST" "2017-12-05 01:00:00 IST" "2017-07-10 23:00:00 IST"

Or use lubridate 或使用lubridate

library(lubridate)
with(df1, ymd_h(paste(year, month, day, hour, sep= ' ')))

since year, month, day, hour are stored in different columns, why not just use ISOdate function? 由于年,月,日,小时存储在不同的列中,为什么不只使用ISOdate函数呢? for instance: 例如:

> ISOdate("2017","12", "05", "01")
[1] "2017-12-05 01:00:00 GMT"

if you don't want to see time zone info, just wrap ISOdate with as.Date 如果您不想查看时区信息,只需将ISOdateas.Date包装as.Date

> as.Date(ISOdate("2017","12", "05", "01"))
[1] "2017-12-05"

But this changes the class of object from POSIXct to Date and (correct me if I'm wrong) does not really remove time zone info. 但这会将对象的类别从POSIXct更改为Date,并且(如果我错了,请更正我)并不能真正删除时区信息。

This was discussed in another question How to convert in both directions between year,month,day and dates in R? 这是在另一个问题中讨论的。 如何在R中的年,月,日和日期之间双向转换?

You can do this directly without making a string using lubridate .您可以直接执行此操作而无需使用lubridate制作字符串。

library(lubridate)

df1 %>%
  mutate(date = make_datetime(year, month, day, hour))

This is probably more reliable than using string parsing.这可能比使用字符串解析更可靠。

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

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