使用data.table而不是data.frame进行子集

时间:2014-11-28 17:40:51

标签: r data.table

我正在处理一个包含300万行和10列的数据框,我正在做一些子集。我下面有一些玩具代码。我的子集需要很长时间。如果我在data.table上使用data.table和subset会更快吗?这是一些玩具代码:

s<-c(100,100,100,800,800,6662,33565,265653262,266532)
p<-c(5,5,5,10,10,10,8,9,10)
name<-c("bob","bob","bob","ed","ed","ed","joe","frank","ted")
time<- as.POSIXct(as.character(c("2014-10-27 18:11:36 PDT","2014-10-27 18:11:37 PDT","2014-10-27 18:11:38 PDT","2014-10-27 18:11:39 PDT","2014-10-27 18:11:40 PDT","2014-10-27 18:11:41 PDT","2014-10-27 19:11:36 PDT","2014-10-27 20:11:36 PDT","2014-10-27 21:11:36 PDT")))
dat<- data.frame(s,p,name,time)
dat

这是数据框:

          s  p  name                time
1       100  5   bob 2014-10-27 18:11:36
2       100  5   bob 2014-10-27 18:11:37
3       100  5   bob 2014-10-27 18:11:38
4       800 10    ed 2014-10-27 18:11:39
5       800 10    ed 2014-10-27 18:11:40
6      6662 10    ed 2014-10-27 18:11:41
7     33565  8   joe 2014-10-27 19:11:36
8 265653262  9 frank 2014-10-27 20:11:36
9    266532 10   ted 2014-10-27 21:11:36

现在我在数据帧上进行了子集:

  result <- subset(dat,    as.numeric(s) == 100
                   &  p == 5
                   &  name  == "bob"
                   & time >= "2014-10-27 18:11:36 PDT"
                   & time <= "2014-10-27 18:12:00 PDT"
                   )
  result

    s p name                time
1 100 5  bob 2014-10-27 18:11:36
2 100 5  bob 2014-10-27 18:11:37
3 100 5  bob 2014-10-27 18:11:38

如何使用data.table执行类似的操作?

谢谢。

1 个答案:

答案 0 :(得分:3)

好吧,由于“时间”选择器,您的示例代码实际上会破坏数据帧 - 您尝试将POSIXlt日期(在数据框中)与字符串(在选择器中)匹配。我想你想要:

result <- subset(dat,    as.numeric(s) == 100
               &  p == 5
               &  name  == "bob"
               & time >= as.POSIXlt("2014-10-27 18:11:36 PDT")
               & time <= as.POSIXlt("2014-10-27 18:12:00 PDT")
               )

result
    s p name                time
1 100 5  bob 2014-10-27 18:11:36
2 100 5  bob 2014-10-27 18:11:37
3 100 5  bob 2014-10-27 18:11:38

这种语法非常适用于data.tables:

dat <- as.data.table(dat)
result <- subset(dat,
              as.numeric(s) == 100
              &  p == 5
              &  name  == "bob"
              & time >= as.POSIXlt("2014-10-27 18:11:36 PDT")
              & time <= as.POSIXlt("2014-10-27 18:12:00 PDT")
)
result

     s p name                time
1: 100 5  bob 2014-10-27 18:11:36
2: 100 5  bob 2014-10-27 18:11:37
3: 100 5  bob 2014-10-27 18:11:38

如果你想要更多像data.table一样的东西,你可以完全避免“子集”,而只是直接对data.table进行操作:

dat <- as.data.table(dat)
result <- dat[as.numeric(s) == 100
              & p == 5
              & name  == "bob"
              & time >= as.POSIXlt("2014-10-27 18:11:36 PDT")
              & time <= as.POSIXlt("2014-10-27 18:12:00 PDT"),]

result 

     s p name                time
1: 100 5  bob 2014-10-27 18:11:36
2: 100 5  bob 2014-10-27 18:11:37
3: 100 5  bob 2014-10-27 18:11:38