首页 > 解决方案 > 在 R 中使用 data.table 制作函数

问题描述

我正在学习用库编写函数data.table。经过实验,我曾经get()将变量转换为对象。想知道是否有更多的实现方式?

library(data.table)

DT <- data.table(
  V1=rep(letters[1:3],5),
  V2=c(2:16)
)

Test1 <- DT[,.((V2-sd(V2))/(max(V2)-min(V2))), by=.(V1)] # for comparision

Norma <- function(dataset, Vari, group_by){
  dataset[,
          .((get(Vari)-sd(get(Vari)))/(max(get(Vari))-min(get(Vari)))),
          by=.(get(group_by))    
    ]
}


Test2 <- Norma(DT,"V2","V1")

它有效,Test1 与 Test2 相同。

标签: rdata.table

解决方案


Instead of get, we can specify the columns of interest where the function needs to be applied in .SDcols and then loop through the columns. Here, it is only one column, so we extract that column as a vector using [[

Norma <- function(dataset, Vari, group_by){
   dataset[,
      .((.SD[[1]]-sd(.SD[[1]]))/(max(.SD[[1]])-min(.SD[[1]]))),
      by= group_by, .SDcols = Vari  
   ]
 }

identical(Norma(DT, "V2", "V1"), Test1)
#[1] TRUE

推荐阅读