Search code examples
rdataframepretty-print

How to increase space between colums when pretty-printing a data-frame?


Let's say I have a data-frame like the one below

x <- read.table(text="
  gross  net.ss      net     rate  gross.m     net.m
  12000 11141.4 10369.25 6.434592 1000.000  864.1041
  12500 11641.4 10761.75 7.037208 1041.667  896.8124
  13000 12141.4 11154.25 7.593469 1083.333  929.5208
  13500 12636.0 11542.51 8.099926 1125.000  961.8758
  14000 13104.0 11909.89 8.529357 1166.667  992.4908
  14500 13572.0 12277.27 8.929172 1208.333 1023.1058
", header = TRUE)

format does a pretty good job at pretty-printing the data-frame, but I find a single space between columns is not enough. It makes the table hard to read IMO.

> format(x, digits = 2, nsmall = 2, big.mark = ",")
   gross    net.ss       net rate  gross.m    net.m
1 12,000 11,141.40 10,369.25 6.43 1,000.00   864.10
2 12,500 11,641.40 10,761.75 7.04 1,041.67   896.81
3 13,000 12,141.40 11,154.25 7.59 1,083.33   929.52
4 13,500 12,636.00 11,542.51 8.10 1,125.00   961.88
5 14,000 13,104.00 11,909.89 8.53 1,166.67   992.49
6 14,500 13,572.00 12,277.27 8.93 1,208.33 1,023.11

Ideally I'd like two spaces between columns. I can't find an option that does that. With the width option you can specify a minimum width, but this makes all columns the same width, which is even worse

> format(x, digits = 2, nsmall = 2, big.mark = ",", width = 9)
       gross     net.ss        net      rate    gross.m      net.m
1     12,000  11,141.40  10,369.25      6.43   1,000.00     864.10
2     12,500  11,641.40  10,761.75      7.04   1,041.67     896.81
3     13,000  12,141.40  11,154.25      7.59   1,083.33     929.52
4     13,500  12,636.00  11,542.51      8.10   1,125.00     961.88
5     14,000  13,104.00  11,909.89      8.53   1,166.67     992.49
6     14,500  13,572.00  12,277.27      8.93   1,208.33   1,023.11

Any ideas?


Solution

  • Maybe with a custom function?

    spaces <- function(x, space = 2){
      s <- rep(" ", space)
      as.data.frame(sapply(x, function(y) paste0(s, y)))
    }
    
    spaces(x)
    spaces(format(x, digits = 2, nsmall = 2, big.mark = ","), 2)