data.table - 除一列外的所有组 [英] data.table - group by all except one column

查看:118
本文介绍了data.table - 除一列外的所有组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我可以使用 data.table 对除了一个列之外的所有列进行分组吗?我有很多列,所以我宁愿避免写出所有的 colnames



我想在表中折叠重复,我知道一个列没有相关性。

  library(data.table) 

DT< - 结构(列表(N = c(1,2,2),val = c(50,60,60),collapse = c(A,
B,C)),.Names = c(N,val,collapse),row.names = c(NA,
-3L),class = c .table,data.frame))

> DT
N val collapse
1:1 50 A
2:2 60 B
3:2 60 C

也就是说,给定 DT 是否有像 DT [,print SD),by =!collapse] 其中:

  DT [,print(.SD),。(N,val)] 
collapse
1:A
collapse
1:B
2:C $ b (N,val)

?我认为我可以通过复制和粘贴列名称,但我认为可能有一些优雅的方式来做到这一点。

解决方案

要对除了一个列之外的所有列进行分组,可以使用:

  by = setdiff )


Can I group by all columns except one using data.table? I have a lot of columns, so I'd rather avoid writing out all the colnames.

The reason being I'd like to collapse duplicates in a table, where I know one column has no relevance.

library(data.table)

DT <- structure(list(N = c(1, 2, 2), val = c(50, 60, 60), collapse = c("A", 
"B", "C")), .Names = c("N", "val", "collapse"), row.names = c(NA, 
-3L), class = c("data.table", "data.frame"))

> DT
   N val collapse
1: 1  50        A
2: 2  60        B
3: 2  60        C

That is, given DT, is there something like like DT[, print(.SD), by = !collapse] which gives:

> DT[, print(.SD), .(N, val)]
   collapse
1:        A
   collapse
1:        B
2:        C

without actually having to specify .(N, val)? I realise I can do this by copy and pasting the column names, but I thought there might be some elegant way to do this too.

解决方案

To group by all columns except one, you can use:

by = setdiff(names(DT), "collapse")

这篇关于data.table - 除一列外的所有组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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