1

我有一个data.table这样的结构:

Classes ‘data.table’ and 'data.frame':  1336 obs. of  5 variables:
 $ timestamp: POSIXct, format: "2013-02-01 00:03:49" "2013-02-01 00:03:49" "2013-02-01 00:07:54" ...
 $ hour     : int  1 1 1 1 1 1 1 1 1 1 ...
 $ price    : num  21 22 21 22 21 22 35 35.5 35.9 38 ...
 $ qty      : num  50 20 50 20 50 20 15 20 3 30 ...
 $ timegroup: int  1 250 506 757 758 1004 1253 1 250 506 ...
 - attr(*, ".internal.selfref")=<externalptr> 

示例数据是:

> df
                timestamp hour price qty timegroup
   1: 2013-02-01 00:03:49    1    21  50         1
   2: 2013-02-01 00:03:49    1    22  20         1
   3: 2013-02-01 00:07:54    1    21  50         1
   4: 2013-02-01 00:07:54    1    22  20         1
   5: 2013-02-01 00:11:59    1    21  50         1
  ---                                             
1332: 2013-04-07 00:12:10    1    40  50         1
1333: 2013-04-07 00:12:10    1    47  50         1
1334: 2013-04-07 00:12:10    1    53  15         1
1335: 2013-04-07 00:12:10    1    78  50         1
1336: 2013-04-07 00:12:10    1   345  25         1

我正在尝试清理数据,因为在不同的时间有重复的条目。例如,第 3 行和第 4 行应该被删除,因为它们与第 1 行和第 2 行是重复的,只是在不同的时间注册。我试图通过生成时间戳组然后比较它们之间的后续组来实现这一点。但是我被困在生成日期时间组上。

groups <- unique(df$timestamp)
df[,timegroup:=which(timestamp==groups)]

但由于某些未知原因,该timegroup列不想创建自己。原因是这个错误,我对我没有多大帮助

Warning messages:
1: In `==.default`(timestamp, groups) :
  longer object length is not a multiple of shorter object length
2: In `[.data.table`(df, , `:=`(timegroup, which(timestamp == groups))) :
  Supplied 7 items to be assigned to 1336 items of column 'timegroup' (recycled leaving remainder of 6 items).

并且循环sapplyfor可以工作。

谁能告诉我为什么?它似乎与格式有关...谢谢。

4

1 回答 1

2

您当前问题的答案是这样的:

df[, timegroup := .GRP, by = timestamp]

我认为我不太了解您所面临的一般问题,无法为此提出解决方案。

我相对疯狂的猜测是你想要这个:

df = data.table(timestamp = c(1,1,2,2,3,3), var1 = c(1,2,1,2,1,3), var2 = c(1,2,1,2,1,4))
groups = unique(df$timestamp)
groups.duplicated = c(FALSE, sapply(seq_along(groups)[-1], function(i) {
    identical(df[timestamp == groups[i-1], -1],
              df[timestamp == groups[i], -1])
}))

df[timestamp %in% groups[!groups.duplicated]]
#   timestamp var1 var2
#1:         1    1    1
#2:         1    2    2
#3:         3    1    1
#4:         3    3    4
于 2013-05-09T21:50:45.973 回答