1

Given a function

testf <- function(dt){

  dt[, t := seq(1:nrow(dt))]
  return(dt)

}

and the data.table:

dt <- data.table(a=1, b=2)

when applying the function on this data.table and not assigning the output to a variable there is for some reason I don't understand no visible output generated.

testf(dt)
#nothing

hoewever, when take the same function but with a print function before it does:

    testf <- function(dt){

      dt[, t := seq(1:nrow(dt))]
      print(dt)
      return(dt)

    }

testd(dt)
   a b t
1: 1 2 1
   a b t
1: 1 2 1

When assigning the Output to a variable the output is however actually stored in that variable, no matter whether a print() function is called within the function or not:

t <- testf(dt)
View(t)
#Output visible

Can anybody explain me what is going wrong here?

yasel
  • 433
  • 3
  • 13
  • You can use `copy()`: `testf <- function(dt){ dt[, t := seq(1:nrow(dt))]; copy(dt) }` – jogo Aug 26 '19 at 13:51
  • https://cran.r-project.org/web/packages/data.table/vignettes/datatable-faq.html#why-do-i-have-to-type-dt-sometimes-twice-after-using-to-print-the-result-to-console – Roland Aug 26 '19 at 13:53
  • I really hope it is not a real function though. No sense running `seq` over `:`. Also, data.table has the `.I` operator too. Regarding your issue, it is a known thing regarding `\`:=\`` and functions, I really hope you've searched before posting – David Arenburg Aug 26 '19 at 14:00
  • Thank you. No real function, just for demonstration purposes – yasel Aug 26 '19 at 14:06

1 Answers1

3

We need to specify the [] after the assignment

testf <- function(dt){

  dt[, t := seq(1:nrow(dt))][]

}
testf(dt)
#  a b t
#1: 1 2 1
akrun
  • 874,273
  • 37
  • 540
  • 662
  • oh thank you! could you maybe explain in which general cases this is necessary? would not have realized – yasel Aug 26 '19 at 13:52
  • 1
    @yasel if you need to return the output into the console, otherwise,w hen you assign it to a object, the value would be there – akrun Aug 26 '19 at 13:53