0

I joined two data.tables, dropped the join column and returned the joined datatable. When the function is called, it returns null. If I print the datatable before return, it returns. Tried other operations like str or setorder even then it did not. Why does this happen?

library(data.table)
dmap <- function(){
    xx = unlist(strsplit('abcpqr', ''))
    div = data.table(division=rep(c('abc', 'pqr'), each=3), state=xx)
    stc = data.table(state=xx, stcd = 1:6)
    div = div[stc, on='state']
    div[, state := NULL]
    # print(str(div))
    # setorder(div, stcd)
    # print(div)
    return(div)
}

dmap()

Tried on MacOS 11.5.2 (20G95) R version 4.0.3 (2020-10-10) -- "Bunny-Wunnies Freak Out" data.table 1.14.1

Red Hat Enterprise Linux release 8.3 (Ootpa) R version 4.0.5 (2021-03-31) -- "Shake and Throw" data.table 1.14.0 using 8 threads

  • 1
    The object is returned, although invisibly. Try `a<-dmap()` then `a` a couple of times. In your function just change `return(div)` with `return(div[])` to make the result visible. – nicola Sep 23 '21 at 10:07
  • Maybe it's to do with lazy evaluation. It needs the `print()` statement to action the lines above in the function. Another alternative is to assign `dmap()` to a variable, e.g. `output <- dmap()` and it will return a data.frame as expected – Tech Commodities Sep 23 '21 at 10:09
  • 1
    Related to @nicola's comment, I think: [FAQ 2.23 Why do I have to type DT sometimes twice after using := to print the result to console?](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) – Henrik Sep 23 '21 at 10:19
  • To be clear, with `return(div)`, it is not returning `NULL`, it's just that typing `div` on the console prints nothing. If it returned `NULL`, then typing `div` on the console (immediately after the last `:=` assignment) would display the literal `NULL`. – r2evans Sep 23 '21 at 15:51
  • Thank you. I had not understood the bugfix. – Baan Bapat Sep 24 '21 at 12:05

0 Answers0