Print named vector without padding

256 Views Asked by At

I have a named character vector like this:

x <- c(a="1.000", b="10000.000", c="1.000")

I want to print it without quotes, leaving a gap of 2 between the values.

print(x, quote=FALSE, print.gap=2)

gives me:

        a          b          c  
    1.000  10000.000      1.000

As can be seen, all values are padded to the width of the widest value. I would like to print it so that it looks like this:

    a          b      c  
1.000  10000.000  1.000

The names may also be longer. For example:

x <- c(aaaaaa="1.000", b="10000.000", ccccccc="1.000")

This should print as:

aaaaaa          b  ccccccc  
 1.000  10000.000    1.000

I don't see how this can be accomplished with existing functions. I wrote this ugly hack:

fun <- function(x) {

   len.n <- nchar(names(x))
   len.x <- nchar(x)
   max.len <- pmax(len.n, len.x)
   for (i in 1:length(x)) {
      cat(rep(" ", (max.len - len.n)[i]), collapse="", sep="")
      if (i > 1)
         cat("  ")
      cat(names(x)[i])
   }
   cat("\n")
   for (i in 1:length(x)) {
      cat(rep(" ", (max.len - len.x)[i]), collapse="", sep="")
      if (i > 1)
         cat("  ")
      cat(x[i])
   }
   cat("\n")

}

x <- c(a="1.000", b="10000.000", c="1.000")
fun(x)
x <- c(aaaaaa="1.000", b="10000.000", ccccccc="1.000")
fun(x)

Any suggestions for a more elegant solution?

1

There are 1 best solutions below

0
On BEST ANSWER

Updated: Fixed minor error

My solution is not so different than yours, but avoids the loops.

NicePrint = function(x) {
  NameW = nchar(names(x))
  ValW  = nchar(x)
  Width = pmax(NameW, ValW)
  format = sapply(Width, function(x) paste("%", x, "s", sep=""))

  L1 = paste(sprintf(format, names(x)), collapse="  ")
  L2 = paste(sprintf(format, x), collapse="  ")
  cat(L1, "\n", L2, "\n", sep="")
}

x <- c(a="1.000", b="10000.000", c="1.000") 
NicePrint(x)
    a          b      c
1.000  10000.000  1.000

x <- c(aaaaaa="1.000", b="10000.000", ccccccc="1.000")
NicePrint(x)
aaaaaa          b  ccccccc
 1.000  10000.000    1.000