Clayton Stanley Clayton Stanley - 2 months ago 7
R Question

An option to not suppress output after := assignment in data.table

This is related to data.table objects not printed after returned from function but is not a dupe. This question is to specifically look for a way to not suppress output when using an assignment

:=
data.table line at the repl. So in cases where an eval would cause R to call the print method.

I've upgraded and noticed that
:=
returns invisibly now. As I develop with an interactive workflow this disrupts the flow when I am building a pipeline, add an assignment
:=
line, and then expect to see the results to use as context for adding an additional step. Sure I can add a
[]
line, but again this disrupts the flow.

I would rather not argue about choosing to return invisibly or not, as I figure this has been thoroughly discussed already, and the correct decision for the majority of people and use cases has been made. Instead, is there an option I can set or workaround to have
:=
not return invisibly?

Answer

One approach in 1.9.6 is to patch the print.data.table S3 method.

Prior to calling the original method, set the .global$print value to "" (default). This undoes how this value was just changed prior to the generic print method being called (using dynamic scoping rules), in the case where data.table would like to return invisibly (e.g., an assignment := line).

Likely a naive solution, as I'm still learning about packages, namespaces, environments, S3 methods, etc.

library(data.table)
print.data.table.orig = get('print.data.table', envir=asNamespace('data.table'))
print.data.table.patch = function(x, ...) {
  .globalRef = get('.global', envir=asNamespace('data.table'))
  .globalRef$print = ""
  print.data.table.orig(x, ...)
}

library(R.methodsS3)
setMethodS3('print', 'data.table', print.data.table.patch) 


fTbl = data.table(x=1:500000)
fTbl[, x := 5]
        x
     1: 5
     2: 5
     3: 5
     4: 5
     5: 5
    ---  
499996: 5
499997: 5
499998: 5
499999: 5
500000: 5

fTbl
        x
     1: 5
     2: 5
     3: 5
     4: 5
     5: 5
    ---  
499996: 5
499997: 5
499998: 5
499999: 5
500000: 5
> 
Comments