按因子获取数据中第n个元素的更有效方法 [英] more efficient way to take every nth element in data.table by factors

查看:66
本文介绍了按因子获取数据中第n个元素的更有效方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

线程讨论了如何对数据进行处理帧。我想做的比这更复杂:

This thread has discussed about doing it for data frame. I want to do a little more complicated than that:

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))
                  )
        )

有哪些更有效的方法 data.table 本机函数?

What are more efficient way(s) to do this with data.table native functions?

推荐答案

data.table ,您可以引用列,就好像它们是dt范围内的变量一样。因此,您不需要 $ 。也就是说,

In data.table, you can refer to columns as if they are variables within the scope of dt. So, you don't need the $. That is,

dt2 = dt[order(A, B)] # no need for dt$

就足够了。并且如果您想为 A A中的每个组的 B 的第四个元素:

is sufficient. And if you want the 4th element of B for every group in A:

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

请参阅@Vlo的答案您的第二个问题。

Refer to @Vlo's answer for your second question.

从您使用 data.table s的方式来看,您似乎已经没有经历任何小插曲或谈话。查阅简介和FAQ会很有帮助。 vignettes 主页上的教程;尤其是马特的@ user2014教程

From the way you're using data.tables, it seems like you've not gone through any vignettes or talks. It'd be helpful for you to check out the Introduction and the FAQ vignettes or tutorials from the homepage; especially, Matt's @user2014 tutorial amidst others.

这篇关于按因子获取数据中第n个元素的更有效方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆