根据 R 中的其他列更改 POSIXct 变量的日期
有没有办法根据其他列的值更改 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 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
首先将
Date
列更新为日期。然后使用 lubridate 将该日期分配给Date_Time
列:如有必要,请将时区更新为所需的任何值:
First update the
Date
column to be a date. Then uselubridate
to assign that date to theDate_Time
column:And if necessary, update the timezone to whatever if needs to be: