簡體   English   中英

在函數中按名稱傳遞data.table列

[英]Pass data.table column by name in function

我想將列名傳遞給函數,並使用列索引和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)

但是,這將返回錯誤:

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

我想我誤會了在R中傳遞裸列名稱的方式。我有什么選擇?

你可以做

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

我建議不要(1) setorder內部的setorder ,因為它有副作用; (2)當您將來可能在少於三行的data.table上使用它時,以1:3索引,產生奇怪的效果; (3)固定3而不是將其作為函數的參數; (4)使用n來命名...只是我個人的喜好保留n用於計數。

假設您的數據集將始終具有3行以上,並且這是您要在該數據表上執行的唯一操作,那么使用setorderv代替可能會符合您的利益。

top3 = function(t, n) {
  setorderv(t, n, -1)
  return ( t[1:3, c("Species", n), with=FALSE])
}

DT = data.table(iris)
top3(DT, "Petal.Width")

結果:

     Species Petal.Width
1: virginica         2.5
2: virginica         2.5
3: virginica         2.5

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM