更有效的方法来获取data.table中的每个第n个元素

bio*_*man 0 r data.table

线程讨论了如何为数据框做这件事.我想做一点比这更复杂的事情:

dt <- data.table(A = c(rep("a", 3), rep("b", 4), rep("c", 5)) , B = rnorm(12, 5, 2))
dt2 <- dt[order(dt$A, dt$B)] # Sorting
# Always shows the factor from A
do.call(rbind, by(
  dt2, dt2$A,
  function(x) data.table(A = x[,A][1], B = x[,B][4])
              )
        )
#This is to reply to Vlo's comment below. If I do this, it will return both row as 'NA'
    do.call(rbind,
        by(dt2, dt2$A, function(x) x[4])
      )
# Take the max value of B according to each factor A
do.call(rbind, by(dt2, dt2$A,
                  function(x) tail(x,1))
                  )
        )
Run Code Online (Sandbox Code Playgroud)

使用data.table本机函数执行此操作的更有效方法是什么?

Aru*_*run 5

data.table,您可以引用列,就好像它们是dt范围内的变量一样.所以,你不需要$.那是,

dt2 = dt[order(A, B)] # no need for dt$
Run Code Online (Sandbox Code Playgroud)

足够了.如果你想要B每个组的第4个元素A:

dt2[, list(B=B[4L]), by=A]
#    A        B
# 1: a       NA
# 2: b 6.579446
# 3: c 6.378689
Run Code Online (Sandbox Code Playgroud)

关于第二个问题,请参阅@ Vlo的答案.

从您使用data.tables 的方式来看,您似乎没有经历任何小插曲或谈话.您可以从主页查看简介和常见问题解答中的小插曲教程,这对您有所帮助; 尤其是马特的@ user2014教程.

  • @Arun,为什么不只是`setkey(dt,A,B)`?因为他创建`dt2`的唯一原因是为了排序`dt` (2认同)