Search code examples
rpretty-print

Pretty printing an R matrix of strings?


I have something like this:

     [,1]                   [,2]                  [,3]
[1,] "75 (0.6, 102.549)"    "6 (23.655, 103.078)" "12 (-33.897, 85.281)"
[2,] "9 (52.26, 46.831)"    "2 (79.672, 66.679)"  "NA (NA, NA)"
[3,] "5 (-38.776, 125.591)" "NA (NA, NA)"         "4 (-25.222, 112.685)"
[4,] "1 (-206.245, NA)"     "NA (NA, NA)"         "NA (NA, NA)"

I am wondering if it's possible to pretty print this matrix, e.g. align each element to right, omit quotes, etc?


Solution

  • You could just convert it to a data.frame, whose default printing method is pretty much what you're asking for:

    ## Easily-reproducible example matrix
    m <- matrix(replicate(12, paste0(sample(letters, sample(1:10)), collapse="")), 
                ncol=3)
    
    ## Print it like a data.frame
    data.frame(m)
    #          X1         X2         X3
    # 1 liqfodhkp    lbvxucd gpizqtxcjr
    # 2 rfeabvshl   egkzjcyr  yuqzbpocd
    # 3     hfuja wlyepibndq    jtnrpsz
    # 4        ei        meq      fbwlg