Grec001
Grec001

Reputation: 1121

Making function with data.table in R

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.

Upvotes: 4

Views: 1506

Answers (1)

akrun
akrun

Reputation: 887108

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

Upvotes: 3

Related Questions