在R中使用data.table进行功能 [英] Making function with data.table in R

查看:40
本文介绍了在R中使用data.table进行功能的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I am learning to write function with the library data.table. After experiments, i used get() to convert a variable to an object. Would like to know if there is more ways to realize it?

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相同.

it works, Test1 is identical to Test2.

推荐答案

我们可以在 .SDcols中指定需要在其中应用功能的列,而不是 get .代码>,然后遍历各列.在这里,它只是一列,因此我们使用 [[[

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

这篇关于在R中使用data.table进行功能的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆