Making function with data.table in R

只愿长相守 提交于 2021-01-27 07:12:43

问题


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")

it works, Test1 is identical to Test2.


回答1:


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


来源:https://stackoverflow.com/questions/50082887/making-function-with-data-table-in-r

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!