使用 lubridate 包合并 R 中的日期及其关联值

Using the lubridate package to merge dates and its associated values in R

这是我第二次就同一数据集发帖。这一次,我在使用包 lubridate.

中的函数 ceiling_date 时遇到了问题

这是我的数据集示例:

> head(dataraw)
                Time ACTIVITY_X ACTIVITY_Y ACTIVITY_Z
 1: 6/19/18 10:40:00         60         74         95
 2: 6/19/18 10:41:20         62         63         88
 3: 6/19/18 10:42:40         60         56         82
 4: 6/19/18 10:44:00         66         61         90
 5: 6/19/18 10:45:20         60         53         80
 6: 6/19/18 10:46:40         57         40         70
 7: 6/19/18 10:48:00         54         41         68
 8: 6/19/18 10:49:20         52         49         71
 9: 6/19/18 10:50:40         61         49         78
10: 6/19/18 10:52:00         93         32         98
11: 6/19/18 10:53:20         80         54         97
12: 6/19/18 10:54:40         73         39         83
13: 6/19/18 10:56:00         47         37         60
14: 6/19/18 10:57:20         51         55         75
15: 6/19/18 10:58:40         51         60         79
16: 6/19/18 11:00:00         14         13         19
17: 6/19/18 11:01:20          0          0          0
18: 6/19/18 11:02:40         13          3         13
19: 6/19/18 11:04:00         20         10         22
20: 6/19/18 11:05:20         13          6         14

这就是我想要转换数据的方式:

                Time     x   y   z
1: 2018-06-19 10:40:00  60  74  95
2: 2018-06-19 10:44:00 188 180 260
3: 2018-06-19 10:48:00 171 134 218
4: 2018-06-19 10:52:00 206 130 247
5: 2018-06-19 10:56:00 200 130 240
6: 2018-06-19 11:00:00 116 128 173
7: 2018-06-19 11:04:00  33  13  35
8: 2018-06-19 11:08:00  13   6  14

每 240 秒(4 分钟)一次,而不是 dataraw 中的 80 秒(1:20 分钟)一次。 ACTIVITY_XACTIVITY_YACTIVITY_Z 的值相加以适应较长的 4 分钟间隔。

下面是我一直在使用的代码。这适用于我发布的示例,但在完整的 dataraw 数据集上使用时,我会收到警告消息和错误,如下所示:

> sampleinput<-na.omit(dataraw)
> names(sampleinput)[1]<-"Time"
> sampleinput$Time <- as.numeric(as.character(sampleinput$Time))
Warning message:
NAs introduced by coercion 
> X <- data.table(sampleinput)
> X$tgroup <- lubridate::ceiling_date(X$Time, '4 mins')
Error in UseMethod("reclass_date", orig) : 
  no applicable method for 'reclass_date' applied to an object of class "c('double', 'numeric')"
> X[, list( x = sum(ACTIVITY_X), 
+           y = sum(ACTIVITY_Y), 
+           z =sum(ACTIVITY_Z) ), by = list (tgroup)]
Error in eval(bysub, x, parent.frame()) : object 'tgroup' not found

这是否与语法或编码错误有关?如果有帮助,完整的 dataraw 数据集可用 here,因为它太大而无法发布为 dput()

感谢任何帮助!

你快到了。日期解析失败。请参阅以下解决方案:

library(lubridate)
library(dplyr)

data <- read.table("41361_sensor_converted.txt", sep="\t", header=TRUE)

data %>% 
 mutate(
  Time      = mdy_hms(data$Time),
  TimeGroup = ceiling_date(Time, '4 mins') ) %>%
 group_by(TimeGroup) %>% 
 summarise(
  x = sum(ACTIVITY_X),
  y = sum(ACTIVITY_Y),
  z = sum(ACTIVITY_Z) )