Search code examples
rdataframeexportpngdigits

How to export a table as PNG from data frame with rounded digits


I have a lot of data frames like df with a few columns and rows. Because of this I searched for something to write my tables directly as png files. So I do not have to produce all the tables by myself in another program.

df <- structure(c(1.688, 2.402, 2.636, 2.656, 2.8, 2.337, 0.261, 0.3, 
0.299, -0.158, -0.79, -0.115, 2.196, 3.067, 3.31, 3.437, 3.526, 
3.012, 1.895, 2.643, 3.31, 3.085, 3.07, 2.735), .Dim = c(6L, 
4L), .Dimnames = list(c("U", "V", "W", "X", "Y", "Z"), c("A", 
"B", "C", "D")))

I have read something about the grid.table (package gridExtra) and the htmlTable (package htmlTable) function and I also tried to do some codes that were already discussed on SO. In my case I have not found a solution yet. Beforehand, both function actually work.

grid.table(df)
htmlTable(df)

In my case and the most scientific work the digits should be the same in the whole table. So a 0.300 should be written as a 0.300 and not a 0.3. As far as I know both functions do not include a round or digits function.

With @jay.sf's code I could fix the problem of the rounded digits.

df <- apply(df, 1:2, formatC, format="f", digits=3)  # format digits

pdf("df.pdf", height = 12, width = 10)
grid.table(df)
dev.off()

So I have found my table with my values rounded by 3 digits. An additional title would be good, but is not absolutely necessary.

Thanks in advance!


Solution

  • There's a way plotting the thing.

    df <- apply(df, 1:2, formatC, format="f", digits=3)  # format digits
    
    # Helper sequences    
    sy <- seq(.9, 0, length.out=nrow(df))
    sx <- seq(0.1, 1, length.out=ncol(df))
    adj <- .03  # for adjustment
    
    png(width=600, height=400, res=100)
    
    par(mar=c(2, 2, 4, 2) + 0.1)
    plot.new()  # initialize plot
    # plot column names
    sapply(seq(ncol(df)), function(x) 
      text(sx[x] - adj, 1 + adj, colnames(df)[x], font=2, xpd=TRUE))
    # plot row names
    sapply(seq(nrow(df)), function(x) 
      text(0 - adj, sy[x], rownames(df)[x], font=2, xpd=TRUE))
    # plot values
    mapply(function(x, y) text(sx[x], sy[y], labels=df[y, x]), 
           rep(seq(ncol(df)), each=nrow(df)), rep(seq(nrow(df)), ncol(df)))
    # plot title
    text(-.05, 1.2, "Good additional title here", xpd=TRUE, cex=1.5, font=2, adj=0)
    
    dev.off()
    

    PNG produced:

    enter image description here