我有一个时间和日期列表,在6个月内每2.5分钟拍摄一次。但是,我的值缺少我需要的seconds元素。我想为丢失的值添加正确的秒数,因此在本例中为00:02:00、00:07:00、00:12:00,应为00:02:30、00:07 :30,00:12:30。如果可能的话,我想在df1$datetime
和df1$time
中这样做。
datetime time date
2018-03-18 00:00:00 00:00:00 18/03/2018
2018-03-18 00:02:00 00:02:00 18/03/2018
2018-03-18 00:05:00 00:05:00 18/03/2018
2018-03-18 00:07:00 00:07:00 18/03/2018
2018-03-18 00:10:00 00:10:00 18/03/2018
2018-03-18 00:12:00 00:12:00 18/03/2018
我已将df1$datetime
转换为POSIXct。
我完全不确定如何在R中执行此操作。理想情况下,我希望能够对运行至26/6/18的整个数据集执行此操作。
任何建议都值得赞赏。
答案 0 :(得分:1)
我们可以添加seconds
library(lubridate)
df1$datetime[c(FALSE, TRUE)] <- df1$datetime[c(FALSE, TRUE)] + seconds(30)
df1$time[c(FALSE, TRUE)] <- format(df1$datetime[c(FALSE, TRUE)], "%H:%M:%S")
df1
# datetime time date
#1 2018-03-18 00:00:00 00:00:00 18/03/2018
#2 2018-03-18 00:02:30 00:02:30 18/03/2018
#3 2018-03-18 00:05:00 00:05:00 18/03/2018
#4 2018-03-18 00:07:30 00:07:30 18/03/2018
#5 2018-03-18 00:10:00 00:10:00 18/03/2018
#6 2018-03-18 00:12:30 00:12:30 18/03/2018
df1 <- structure(list(datetime = structure(c(1521345600, 1521345720,
1521345900, 1521346020, 1521346200, 1521346320), class = c("POSIXct",
"POSIXt"), tzone = ""), time = c("00:00:00", "00:02:00", "00:05:00",
"00:07:00", "00:10:00", "00:12:00"), date = c("18/03/2018", "18/03/2018",
"18/03/2018", "18/03/2018", "18/03/2018", "18/03/2018")), row.names = c(NA,
-6L), class = "data.frame")