Skip to content

Instantly share code, notes, and snippets.

@gavinsimpson
Last active September 7, 2016 05:32
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save gavinsimpson/2b49f3026b50eeba29314398e27a6770 to your computer and use it in GitHub Desktop.
Save gavinsimpson/2b49f3026b50eeba29314398e27a6770 to your computer and use it in GitHub Desktop.
Create a MySQL-like ASCII table of data
asciify <- function(df, pad = 1, ...) {
## error checking
stopifnot(is.data.frame(df))
## internal functions
SepLine <- function(n, pad = 1) {
tmp <- lapply(n, function(x, pad) paste(rep("-", x + (2* pad)),
collapse = ""),
pad = pad)
paste0("+", paste(tmp, collapse = "+"), "+")
}
Row <- function(x, n, pad = 1) {
foo <- function(i, x, n) {
fmt <- paste0("%", n[i], "s")
sprintf(fmt, as.character(x[i]))
}
rowc <- sapply(seq_along(x), foo, x = x, n = n)
paste0("|", paste(paste0(rep(" ", pad), rowc, rep(" ", pad)),
collapse = "|"),
"|")
}
## convert everything to characters
df <- as.matrix(df)
## nchar in data
mdf <- apply(df, 2, function(x) max(nchar(x)))
## nchar in names
cnames <- nchar(colnames(df))
## max nchar of name+data per elements
M <- pmax(mdf, cnames)
## write the header
sep <- SepLine(M, pad = pad)
writeLines(sep)
writeLines(Row(colnames(df), M, pad = pad))
writeLines(sep)
## write the rows
for(i in seq_len(nrow(df))) {
## write a row
writeLines(Row(df[i,], M, pad = pad))
## write separator
writeLines(sep)
}
invisible(df)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment