如何将05:30添加到时间列?

时间:2017-01-02 12:32:04

标签: r dplyr lubridate

在我的数据框中,我想将5小时和30分钟添加到时间列,然后将时间字段分组为2小时(0-2,3-6 ..像这样直到21-23)。以下是数据框:

Time      Date          Device
7:12:20   12/14/2016    Tablet
8:57:34   12/12/2016    Desktop
18:48:36  12/1/2016     Desktop
4:27:34   12/16/2016    Desktop
5:57:48   12/28/2016    Desktop
10:28:31  12/20/2016    Desktop
10:28:32  12/20/2016    Desktop

3 个答案:

答案 0 :(得分:2)

类似的东西:

hms("20:00:00") + hm("5:30")

将产生一个持有的对象:

## [1] "25H 30M 0S"

不完全有用(在此上下文中)。

这是一种添加时间和创建休息的方法:

df <- read.table(text="Time      Date          Device
7:12:20   12/14/2016    Tablet
8:57:34   12/12/2016    Desktop
18:48:36  12/1/2016     Desktop
4:27:34   12/16/2016    Desktop
5:57:48   12/28/2016    Desktop
10:28:31  12/20/2016    Desktop
10:28:32  12/20/2016    Desktop", header=TRUE, stringsAsFactors=FALSE)

library(lubridate)
library(magrittr)

(mdy_hms(sprintf("%s %s", df$Date, df$Time)) + hm("5:30")) %>%
  hour() %>%
  cut(breaks=seq(0, 24, 2), include.lowest=TRUE)
## [1] (10,12] (12,14] [0,2]   (8,10]  (10,12] (14,16] (14,16]
## 12 Levels: [0,2] (2,4] (4,6] (6,8] (8,10] (10,12] (12,14] ... (22,24]

答案 1 :(得分:1)

这将是处理您案件的一种方法。您的数据在此处称为mydf。首先,您可以使用paste()as.POSIXct()创建日期对象。由于您要添加2小时30分钟,我将60(秒)* 150(分钟)添加到日期对象并创建foo。然后,我从foo中提取了小时 - 分钟 - 秒部分,并创建了一个名为Time2的新列。最后一项工作是使用cut()创建一个组变量。我不知道你要如何标记组,所以我将它们命名为组1,组2,依此类推。

library(dplyr)

mydf %>%
mutate(foo = as.POSIXct(paste(Date, Time, sep = " "),
                format("%m/%d/%Y %H:%M:%S"), tz = "UTC") +
                (60 * 150),
       Time2 = format(foo, "%H:%M:%S"),
       group = cut(as.numeric(format(foo, "%H")), breaks = seq(0, 24, 3),
                   labels = paste("group", 1:8, sep = " "),
                   include.lowest = TRUE)) %>%
select(-foo)

#      Time       Date  Device    Time2    group
#1  7:12:20 12/14/2016  Tablet 09:42:20  group 3
#2  8:57:34 12/12/2016 Desktop 11:27:34  group 4
#3 18:48:36  12/1/2016 Desktop 21:18:36  group 7
#4  4:27:34 12/16/2016 Desktop 06:57:34  group 2
#5  5:57:48 12/28/2016 Desktop 08:27:48  group 3
#6 10:28:31 12/20/2016 Desktop 12:58:31  group 4
#7 10:28:32 12/20/2016 Desktop 12:58:32  group 4

DATA

mydf <- structure(list(Time = c("7:12:20", "8:57:34", "18:48:36", "4:27:34", 
"5:57:48", "10:28:31", "10:28:32"), Date = c("12/14/2016", "12/12/2016", 
"12/1/2016", "12/16/2016", "12/28/2016", "12/20/2016", "12/20/2016"
), Device = c("Tablet", "Desktop", "Desktop", "Desktop", "Desktop", 
"Desktop", "Desktop")), .Names = c("Time", "Date", "Device"), class = "data.frame", row.names = c(NA, 
-7L))

答案 2 :(得分:0)

有多种方法可以做到。

案例1:将5小时30分钟转换为秒并将其添加到时间列。

*我必须在添加时间之前更喜欢,即5小时30分钟,您必须合并时间和日期列,以防您在2100小时附近有时间导致更改日期*

加入列后,请继续执行以下操作:

dataframe$newtime <- as.POSIXct(dataframe$dateandtimetogether) + noofseconds

案例2:定义小时和分钟的功能

在这种情况下你必须加入日期和时间栏,以后可以轻松分开

hrs <- function(u) {
  x <- u * 3600
return(x)
}

mns <- function(m) {
  x <- m * 60
  return(x)
}


dataframe$newtime <- as.POSIXct(dataframe$dateandtimetogether)  + hrs(5) + mns(30)