Search code examples
rpretty-print

print(list(1,2,3)) is long and ugly; how to print lists using print [ie, pretty-printing without having to switch between print vs paste0]


I often get tired of writing this idiom for my console pretty-printing:

writeLines(paste0(“a=“, someObj))

and so I do this:

wp = function(obj) {
    writeLines(paste0(obj))
}

The reason I use paste0 above is because it collapses list‘s nicely:

print(list(1,2)) :

[[1]]
[1] 1

[[2]]
[2] 2     # ah... my eyes >.<

vs paste0(list(1,2),collapse=‘,’):

[1]  “1,2,3”    # ahhh much better

• However, the wp function doesn’t print an obj of type matrix nicely due to paste0:

m = matrix(list(1,2,3,4),nrow=2,byrow=T) paste0(m)

[1] “1” “3” “2” “4”    # yikes, this is supposed to be a matrix... my eyes

This quickly looks super ugly if

m=matrix(list(list(1,2),list(3,4),list(5,6),list(7,8)),nrow=2,byrow=T) paste0(m)

[1] “list(1, 2)” “list(5, 6)” “list(3, 4)” “list(7, 8)”   # yikes again

whereas now, conversely, print does the better job for compact-printing of matrices:

m=matrix(list(list(1,2),list(3,4),list(5,6),list(7,8)),nrow=2,byrow=T) print(m)

      [,1]    [,2]
[1,]  List,2  List,2
[2,]  List,2  List,2   # ah.. much better...

• So my question is, how to make a better wp pretty-printer without inserting obscene dynamic type checks everywhere:

wp = function(obj) {
   if (typeof(obj) == ‘matrix’)
      writeLines(print(obj))
   else if (typeof(obj) == ‘list’)
      writeLines(paste0(obj,collapse=‘,’))
   else 
      # etc ...
}

There must be a better way to do this in base-R. I prefer having my own compact utils instead of including a bunch of packages, but feel free to offer package solutions if it really does boil down to doing dynamic type checks.


Solution

  • You can overwrite the print methods - even the ones for built-in types.

    print.list <- function(x, ...) {
      writeLines(paste0(x, collapse = ","))
    }
    
    print(list(1, 2))
    #> 1,2
    

    Or, you can create your own function.

    wp <- function(x, ...) {
      UseMethod("wp")
    }
    
    wp.default <- print
    
    wp.list <- function(x, ...) {
      writeLines(paste0(x, collapse = ","))
    }
    
    wp(list(1, 2))
    #> 1,2
    
    wp(matrix(1:6, nrow = 2))
    #>      [,1] [,2] [,3]
    #> [1,]    1    3    5
    #> [2,]    2    4    6