为什么使用`which`的这个赋值在`data.table`中不起作用?

时间:2013-05-09 21:18:14

标签: r data.table

我有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循环也可以正常工作。

谁能告诉我为什么?它似乎与格式有某种联系......谢谢。

1 个答案:

答案 0 :(得分: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,with=F],
              df[timestamp == groups[i],-1,with=F])
}))

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