1

I confused when I created the following simple function. If I do not assign the class in the temp then I see nothing on the screen when I execute the function (without print or assigning to anything)

library(dplyr)
library(data.table)
    my_percentage <- function(datatable, variable ){ 
            temp <- datatable[, .N, keyby = c(variable)]
            temp[, percentage := N/sum(N)]
             # temp <- as.data.table(temp)
            return(temp)
    }

my_percentage(iris %>% as.data.table(), variable = "Species")
# print(my_percentage(iris %>% as.data.table(), variable = "Species"))

However if I assign any class in the object that I will return it will be fine.

my_percentage <- function(datatable, variable ){ 
            temp <- datatable[, .N, keyby = c(variable)]
            temp[, percentage := N/sum(N)]
            temp <- as.data.table(temp)
            return(temp)
    }

my_percentage(iris %>% as.data.table(), variable = "Species")

Can anyone explain to me why ?

MrFlick
  • 195,160
  • 17
  • 277
  • 295
George Sotiropoulos
  • 1,864
  • 1
  • 22
  • 32
  • 1
    `my_percentage(data.table(iris), "Species")[]` works for me. Generally, you have to do `[]` after a `:=` inside a function, thanks to a quirk. – Frank Sep 08 '17 at 16:57

0 Answers0