根据日期范围和data.table中的标识符有条件地选择多个项目

时间:2018-07-03 11:51:09

标签: r data.table date-range posixct

我有一个data.table,其中包含单元标识符,设置标识符和对此设置有效的数据范围。我需要提取特定日期的特定单位标识符的设置。下面的最小工作示例显示了如何获得结果。

library(data.table)
settingstable=data.table(UNITID=c(1,1,1,2,2,2,3,4,5,6,6),
                     STARTDATE=as.POSIXct(c("2018-01-01","2018-02-28","2018-06-01","2018-01-01","2018-04-01","2018-06-01","2018-01-01","2018-01-01","2018-01-01","2018-01-01","2018-05-01")),
                     ENDDATE=as.POSIXct(c("2018-02-28","2018-05-31","2018-12-31","2018-03-31","2018-05-31","2018-12-31","2018-12-31","2018-12-31","2018-12-31","2018-04-30","2018-12-31")),
                     SETTINGS=c(1,2,3,4,5,6,7,8,9,10,11))
selectunits=c(2,4,6)
selectdays=as.POSIXct(c("2018-04-02","2018-05-03","2018-02-01"))

resultsettings=NULL
for (i in 1:length(selectunits)) {
  resultsettings=rbind(resultsettings,settingstable[UNITID==selectunits[i] & STARTDATE <= selectdays[i] & ENDDATE >= selectdays[i],.(UNITID,SETTINGS)])
}

对于大数据表或大量单位和天数,这将非常低效。我希望可以与by=UNITID进行分组,但是很遗憾,这是不可能的,因为以下内容会导致longer object length is not a multiple of shorter object length错误。

resultsettings=settingstable[UNITID %in% selectunits & STARTDATE <= selectdays & ENDDATE >= selectdays,.(UNITID,SETTINGS),by=UNITID]

如何改善代码,使其运行效率更高?

1 个答案:

答案 0 :(得分:0)

您可以使用非等额联接:

settingstable[.(u = selectunits, d = selectdays), 
  on=.(UNITID = u, STARTDATE <= d, ENDDATE >= d), 
  .(UNITID, SETTINGS)]

   UNITID SETTINGS
1:      2        5
2:      4        8
3:      6       10

语法为x[i, on=, j]

  • 列表i = .(u = selectunits, d = selectdays)被视为表,将被连接到x = settingstable
  • 如果根据ix中有on=,则通过查找每一行来进行联接。
  • j中,我们可以转换结果。 (如果没有j,我们将只获得联接表。)

如果您的on=条件产生多个匹配项,它们都将出现在结果中。如果它们不匹配,SETTINGSx中的其他列将为NA(尽管可以使用nomatch=参数进行调整)。