Created
February 20, 2026 20:49
-
-
Save grantmcdermott/08902a3645fb8585b7d38d9596d4dde7 to your computer and use it in GitHub Desktop.
Nice(r) base R data.frame print method
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| print.data.frame = function(x, ..., topn = 5, nrows = 20) { | |
| nr = nrow(x) | |
| if (nr <= nrows) { | |
| out = x | |
| splitprint = FALSE | |
| } else { | |
| out = rbind(head(x, topn), tail(x, topn)) | |
| splitprint = TRUE | |
| } | |
| # Type abbreviations | |
| type_map = c( | |
| numeric = "<num>", integer = "<int>", character = "<chr>", | |
| factor = "<fct>", logical = "<lgl>", Date = "<Date>", | |
| POSIXct = "<dttm>", complex = "<cpl>", ordered = "<ord>" | |
| ) | |
| classes = sapply(x, \(col) class(col)[1]) | |
| abbs = unname(type_map[classes]) | |
| abbs[is.na(abbs)] = paste0("<", classes[is.na(abbs)], ">") | |
| names(abbs) = colnames(x) | |
| # Format each column right-justified, build character matrix | |
| cols = lapply(out, \(col) format(col, ..., justify = "right")) | |
| toprint = do.call(cbind, cols) | |
| dimnames(toprint) = list(rownames(out), colnames(x)) | |
| # Set rownames for default integer indices | |
| if (identical(rownames(x), as.character(seq_len(nr)))) { | |
| rn = if (splitprint) { | |
| c(seq_len(topn), seq.int(to = nr, length.out = topn)) | |
| } else { | |
| seq_len(nr) | |
| } | |
| rownames(toprint) = format(rn, right = TRUE) | |
| } | |
| # Prepend class row | |
| toprint = rbind(abbs, toprint) | |
| rownames(toprint)[1] = " " | |
| # Insert separator | |
| if (splitprint) { | |
| sep_row = matrix("", 1, ncol(toprint)) | |
| toprint = rbind( | |
| head(toprint, topn + 1), | |
| sep_row, | |
| tail(toprint, topn) | |
| ) | |
| rownames(toprint)[topn + 2] = "---" | |
| rownames(toprint) = format(rownames(toprint), justify = "right") | |
| } | |
| print(toprint, right = TRUE, quote = FALSE) | |
| invisible(x) | |
| } |
Author
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Use the above function interactively, or add it to your
.Rprofileto make it your defaultdata.framemethod.Examples: