【问题标题】:How do I combine year month date time into a single datetime column using DBI in R?如何使用 R 中的 DBI 将年月日期时间组合成单个日期时间列?
【发布时间】:2022-06-28 13:07:59
【问题描述】:

这是我的源数据 csv、df 的示例:

    Year             : int  2005 2005 2005 2005 2005 2005 2005 2005 2005 2005 ...
    Month            : int  1 1 1 1 1 1 1 1 1 1 ...
    DayofMonth       : int  28 29 30 31 2 3 4 5 6 7 ...
    Time             : int  1605 1605 1610 1605 1900 1900 1900 1900 1900 1900

如何使用 SQLite 而不是 dplyr 将 4 列合并到我的数据库中的日期时间列中?

我希望输出可以类似于:2005-01-29 09:30:00 这样我就可以绘制图表了。

【问题讨论】:

  • 有什么想法吗,里奥?答案有帮助吗?

标签: r sqlite dbi


【解决方案1】:

你可以使用lubridate::make_datetime:

Year =c(2005, 2005, 2005)
Month = c(1,2,3) 
DayofMonth = c(  28, 28, 30)
Time = c(1605, 1605, 1610)


lubridate::make_datetime(Year,Month,DayofMonth,floor(Time/100),Time%%100)

[1] "2005-01-28 16:05:00 UTC" "2005-02-28 16:05:00 UTC" "2005-03-30 16:10:00 UTC"

【讨论】:

    【解决方案2】:

    Base R,使用 Waldi 的样本数据(谢谢!):

    with(df, as.POSIXct(sprintf("%i-%02i-%i %02i:%02i:00", 
      Year, Month, DayofMonth, Time %/% 100, Time %% 100))
    )
    # [1] "2005-01-28 16:05:00 EST" "2005-02-28 16:05:00 EST" "2005-03-30 16:10:00 EST"
    

    这是(可能是天真的)假设您从来没有没有“有意义”的秒或小数分钟或Time 值(即超过 59 分钟,超过 23 小时)。


    数据

    df <- structure(list(Year = c(2005, 2005, 2005), Month = c(1, 2, 3), DayofMonth = c(28, 28, 30), Time = c(1605, 1605, 1610)), class = "data.frame", row.names = c(NA, -3L))
    

    【讨论】:

      猜你喜欢
      • 2018-06-17
      • 2021-11-17
      • 1970-01-01
      • 2019-02-20
      • 2017-10-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-04-21
      相关资源
      最近更新 更多