The question probably generalizes to printing any type of multiline output, and keeping the columns aligned. My actual issue concerns the output of summary.default.
I'm trying to add indentation of a multiple of two to cat output of the summary.default function. I've made some attempts using cat and print, also consulting some related answers, but they all fail so far.
f <- function(x) {
s <- summary.default(x)
liner <- Reduce(paste0, rep("-", 70))
cat("\n", liner, "\n") ## ATT 1. -------------------------------
cat("\n", "foo first attempt", "\n")
cat("\n--|\n")
print(round(s, 3)) #
cat("\n----|\n")
cat("\n *additional information\n")
cat("\n", liner, "\n") ## ATT 2. -------------------------------
cat("\n", "foo second attempt", "\n")
cat("\n--|\n")
print(unname(as.data.frame(cbind(" ", t(attr(s, "names"))))), row.names=F) #
print(unname(as.data.frame(cbind(" ", t(round(unclass(s), 3))))), row.names=F) #
cat("\n----|\n")
cat("\n *additional information\n")
cat("\n", liner, "\n") ## ATT 3. -------------------------------
cat("\n", "foo third attempt", "\n")
cat("\n--|\n")
cat("\n ", attr(s, "names"), "\n")
cat("\n ", round(s, 3), "\n") #
cat("\n----|\n")
cat("\n *additional information\n")
}
> x <- rnorm(100)
> f(x)
----------------------------------------------------------------------
foo first attempt
--|
Min. 1st Qu. Median Mean 3rd Qu. Max.
-2.069 -0.654 -0.092 -0.075 0.696 1.997
----|
*additional information
----------------------------------------------------------------------
foo second attempt
--|
Min. 1st Qu. Median Mean 3rd Qu. Max.
-2.069 -0.654 -0.092 -0.075 0.696 1.997
----|
*additional information
----------------------------------------------------------------------
foo third attempt
--|
Min. 1st Qu. Median Mean 3rd Qu. Max.
-2.069 -0.654 -0.092 -0.075 0.696 1.997
----|
*additional information
The ---| symbolize the required indentation. First attempt does not have any indentation. Second attempt is better, but there's additional space between the lines, and does not generalize when rounding to different digits. At attempt 3 the columns are no longer aligned.
How can I get the desired output using features that come with R?
Desired output:
----------------------------------------------------------------------
foo some text
Min. 1st Qu. Median Mean 3rd Qu. Max.
-2.069 -0.654 -0.092 -0.075 0.696 1.997
*additional information