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

后端 未结 1 596
南笙
南笙 2021-01-29 13:33

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 usi

相关标签:
1条回答
  • 2021-01-29 14:07

    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).

    The effect is that the custom print method for data.table is still called, but data.table no longer tries to modify R's default logic to decide when and when not to print.

    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
    > 
    
    0 讨论(0)
提交回复
热议问题