﻿ 在函数中使用data.table i和j参数 - 代码日志

#### 在函数中使用data.table i和j参数

``````data(mtcars)
mtcars\$car <- factor(gsub("(.*?) .*", "\\1", rownames(mtcars)), ordered=TRUE)
mtcars <- data.table(mtcars)
``````

``````mtcars[, list(Total=length(mpg)), by="car"][order(car)]

car Total
AMC     1
Camaro     1
...
Toyota     2
Valiant     1
Volvo     1
``````

``````group <- "car"
mtcars[, list(Total=length(mpg)), by=eval(group)]
``````

``````mtcars[, list(Total=length(mpg)), by=eval(group)][order(group)]
car Total
Mazda     2
``````

``````tableOrder <- function(x, group){
x[, list(Total=length(mpg)), by=eval(group)][order(group)]
}

tableOrder(mtcars, "car")
``````

``````group = quote(car)
mtcars[, list(Total=length(mpg)), by=group][order(group)]
group Total
AMC     1
...
Toyota     2
Valiant     1
Volvo     1
``````

``````tableOrder = function(x,.expr) {
.expr = substitute(.expr)
ans = x[,list(Total=length(mpg)),by=.expr]
setkeyv(ans, head(names(ans),-1))    # see below re feature request #1780
ans
}

tableOrder(mtcars, car)
.expr Total
AMC     1
Camaro     1
...
Toyota     2
Valiant     1
Volvo     1

tableOrder(mtcars, substring(car,1,1))  # an expression, not just a column name
.expr Total
[1,]     A     1
[2,]     C     3
[3,]     D     3
...
[8,]     P     2
[9,]     T     2
[10,]     V     2

tableOrder(mtcars, list(cyl,gear%%2))   # by two expressions, so head(,-1) above
cyl gear Total
[1,]   4    0     8
[2,]   4    1     3
[3,]   6    0     4
[4,]   6    1     3
[5,]   8    1    14
``````

``````tableOrder = function(x,.expr) {
.expr = substitute(.expr)
x[,list(Total=length(mpg)),keyby=.expr]
}
``````

http://stackoverflow.com/questions/9705488/using-data-table-i-and-j-arguments-in-functions