R,data.table,按列分组*数字*和总和列

viv*_*man 1 r data.table

假设我有以下data.table

> DT
#        A B C D E          N
#     1: J t X D N 0.07898388
#     2: U z U L A 0.46906049
#     3: H a Z F S 0.50826435
#    ---                     
#  9998: X b R L X 0.49879990
#  9999: Z r U J J 0.63233668
# 10000: C b M K U 0.47796539
Run Code Online (Sandbox Code Playgroud)

现在我需要按一对列进行分组并计算总和N.当您事先知道列名时,这很容易做到:

> DT[, sum(N), by=.(A,B)]
#      A B        V1
#   1: J t  6.556897
#   2: U z  9.060844
#   3: H a  4.293426
#  ---              
# 674: V z 11.439100
# 675: M x  1.736050
# 676: U k  3.676197
Run Code Online (Sandbox Code Playgroud)

但我必须在一个函数中执行此操作,该函数接收列索引的向量以进行分组.

> f <- function(columns = 1:2) {
    DT[, sum(N), by=columns]
}
> f(1:2)
Error in `[.data.table`(DT, , sum(N), by = columns) : 
  The items in the 'by' or 'keyby' list are length (2). Each must be same 
  length as rows in x or number of rows returned by i (10000). 
Run Code Online (Sandbox Code Playgroud)

我也尝试过:

> f(list("A", "B"))
Error in `[.data.table`(DT, , sum(N), by = list(columns)) : 
  column or expression 1 of 'by' or 'keyby' is type list. Do not quote column
  names. Usage: DT[,sum(colC),by=list(colA,month(colB))]
Run Code Online (Sandbox Code Playgroud)

我该如何使它工作?

A5C*_*2T1 5

这是我如何处理这个问题:

f <- function(columns) {
  Get <- if (!is.numeric(columns)) match(columns, names(DT)) else columns
  columns <- names(DT)[Get]
  DT[, sum(N), by = columns]
}
Run Code Online (Sandbox Code Playgroud)

第一行(Get..)将"列"保持为数字(如果它已经是数字),或者如果它们不是,则将它从字符转换为数字.


使用一些示例数据测试它:

set.seed(1)
DT <- data.table(
  A = sample(letters[1:3], 20, TRUE),
  B = sample(letters[1:5], 20, TRUE),
  C = sample(LETTERS[1:2], 20, TRUE),
  N = rnorm(20)
)

## Should work with either column number or name
f(1)
f("A")
f(c(1, 3))
f(c("A", "C"))
Run Code Online (Sandbox Code Playgroud)