使用其他2列中的元素完成R中列中的元素

时间:2017-03-17 12:51:49

标签: r date

我有一个包含以下数据的.csv文件:

duration time | starting time | finish time 
1,#1996-06-18 23:25:00#,#1996-06-18 23:26:00#

23,#1996-06-18 23:28:00#,#1996-06-18 23:51:00#

1,#1996-06-18 23:59:00#,#1996-06-19#

1,#1996-06-18 23:24:00#,#1996-06-18 23:25:00#

8,#1996-06-18 23:51:00#,#1996-06-18 23:59:00#

3,#1996-06-19#,#1996-06-19 00:03:00#

12,#1996-06-19 00:12:00#,#1996-06-19 00:24:00#

3,#1996-06-18 23:03:00#,#1996-06-18 23:06:00#

粗体线条不完整。我的问题是如何使用持续时间和其他元素完成那些元素(开始时间和结束时间),即将持续时间和开始时间相加以获得结束时间 in R(假设该数据在数据框中)。

基本上,如何将00:00:00添加到这些行(在R数据框中)?

1 个答案:

答案 0 :(得分:0)

您可以使用lubridate包将持续时间列转换为时间对象。使用dplyr包,您可以按如下方式操作data.frame:

library(dplyr)
library(magrittr)
library(lubridate)
df <- data.frame(duration = c(1, 23, 1, 1, 8, 3),
             start_time = c("1996-06-18 23:25:00",
                            "1996-06-18 23:28:00",
                            "1996-06-18 23:59:00",
                            "1996-06-18 23:24:00",
                            "1996-06-18 23:51:00",
                            "1996-06-19"),
             end_time = c("1996-06-18 23:26:00", 
                          "1996-06-18 23:51:00", 
                          "1996-06-19",
                          "1996-06-18 23:25:00", 
                          "1996-06-18 23:59:00",
                          "1996-06-19 00:03:00"))

df1 <- df %>% 
  mutate(start_time = as.POSIXct(start_time, format = "%Y-%m-%d %H:%M:%S"), duration = minutes(duration),
         end_time = as.POSIXct(end_time, format = "%Y-%m-%d %H:%M:%S")) %>%
  mutate(start_time = ifelse(is.na(start_time),
                             (end_time - duration),
                             start_time),
         end_time = ifelse(is.na(end_time), 
                          (start_time + duration),
                          end_time))

df1 %<>%
  mutate(start_time = as.POSIXct(start_time, origin = "1970-01-01"),
         end_time = as.POSIXct(end_time, origin = "1970-01-01"))

然后您的输出将如下所示:

> df1
  duration          start_time            end_time
1    1M 0S 1996-06-18 23:25:00 1996-06-18 23:26:00
2   23M 0S 1996-06-18 23:28:00 1996-06-18 23:51:00
3    1M 0S 1996-06-18 23:59:00 1996-06-19 00:00:00
4    1M 0S 1996-06-18 23:24:00 1996-06-18 23:25:00
5    8M 0S 1996-06-18 23:51:00 1996-06-18 23:59:00
6    3M 0S 1996-06-19 00:00:00 1996-06-19 00:03:00