根据 R 中的其他列更改 POSIXct 变量的日期

发布于 2025-01-13 06:06:52 字数 903 浏览 3 评论 0原文

有没有办法根据其他列的值更改 dttm 列的日期? “Date_Time”列中的时间是正确的,但需要更改日期以匹配“Date”列(或所有三列“Year”、“Month”和“Day”)中的日期。

这可能接近我需要做的,但它给了我这个错误:

library(lubridate)
    df$new <- with(df, ymd_hm(sprintf('%04d%02d%02d', Year, Month, day, Time))) #'Time' is new character column of just time component from 'Date_Time'
    
    # Not sure what this means..
    invalid format '%04d'; use format %s for character objects

        > head(df,5)
    # A tibble: 5 x 5
      Date       Year  Month   Day Date_Time          
      <chr>      <fct> <dbl> <dbl> <dttm>             
    1 2020-11-14 2020     11    14 1899-12-31 10:46:00
    2 2020-11-14 2020     11    14 1899-12-31 10:57:00
    3 2020-11-14 2020     11    14 1899-12-31 09:16:00
    4 2012-8-11  2012      8    11 1899-12-31 14:59:00
    5 2012-8-11  2012      8    11 1899-12-31 13:59:00

Is there a way to change the date of a dttm column based on the values from other columns? The time in the "Date_Time" column is correct, but the dates need to be changed to match those in the column "Date" (or from all three columns "Year", "Month", and "Day").

This is likely close to what I need to do, but it gives me this error:

library(lubridate)
    df$new <- with(df, ymd_hm(sprintf('%04d%02d%02d', Year, Month, day, Time))) #'Time' is new character column of just time component from 'Date_Time'
    
    # Not sure what this means..
    invalid format '%04d'; use format %s for character objects

        > head(df,5)
    # A tibble: 5 x 5
      Date       Year  Month   Day Date_Time          
      <chr>      <fct> <dbl> <dbl> <dttm>             
    1 2020-11-14 2020     11    14 1899-12-31 10:46:00
    2 2020-11-14 2020     11    14 1899-12-31 10:57:00
    3 2020-11-14 2020     11    14 1899-12-31 09:16:00
    4 2012-8-11  2012      8    11 1899-12-31 14:59:00
    5 2012-8-11  2012      8    11 1899-12-31 13:59:00

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

嘿看小鸭子会跑 2025-01-20 06:06:52

首先将 Date 列更新为日期。然后使用 lubridate 将该日期分配给 Date_Time 列:

df$Date <- as.Date(df$Date)
lubridate::date(df$Date_Time) <- df$Date

如有必要,请将时区更新为所需的任何值:

attr(df$Date_Time, "tzone") <- "Europe/Paris" # Update timezone

First update the Date column to be a date. Then use lubridate to assign that date to the Date_Time column:

df$Date <- as.Date(df$Date)
lubridate::date(df$Date_Time) <- df$Date

And if necessary, update the timezone to whatever if needs to be:

attr(df$Date_Time, "tzone") <- "Europe/Paris" # Update timezone
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文