在函数中按名称传递data.table列

tke*_*win 5 r data.table

我想将列名传递给函数并使用列索引和setorder函数:

require(data.table)
data(iris)

top3 = function(t, n) {
  setorder(t, n, order=-1)
  return ( t[1:3, .(Species, n)])
}

DT = data.table(iris)
top3(DT, Petal.Width)
Run Code Online (Sandbox Code Playgroud)

但是,这会返回错误:

Error in setorderv(x, cols, order, na.last) : some columns are not in the data.table: n,1

我想我误解了如何在R中传递裸列名称.我有什么选择?

Fra*_*ank 7

你可以做

top3 = function(DT, nm) eval(substitute( DT[order(-nm), .(Species, nm)][, head(.SD, 3L)] ))
top3(DT, Petal.Width)

     Species Petal.Width
1: virginica         2.5
2: virginica         2.5
3: virginica         2.5
Run Code Online (Sandbox Code Playgroud)

我建议反对(1)setorder函数内部,因为它有副作用; (2)索引与1:3你在未来少于三行的data.table上使用它时,会产生奇怪的效果; (3)修正3而不是使其成为函数的参数; (4)n用于名称...仅仅是我个人倾向于保留n计数.