r-lib / pillar

Format columns with colour
https://pillar.r-lib.org/
Other
178 stars 37 forks source link

Show colour in `glimpse()` #658

Open oloverm opened 8 months ago

oloverm commented 8 months ago

I'd love for glimpse() to show colour the same way that tibbles do, to easily notice NAs etc. Currently it can be a bit hard to take in as an undifferentiated wall of text. Perhaps colouring the commas that separate the values in the same dim colour used for the column type would help too.

krlmlr commented 8 months ago

Good idea. Would you like to contribute a PR? What kind of guidance would you need?

ryanzomorrodi commented 5 months ago

I also think it would be a nice feature to have NAs have more color for tables. I can send a PR if you'd like. The coloring of the commas seems like some more intensive work.

My thoughts

format_glimpse.default <- function(x, ...) {
  dims <- dim(x)

  if (!is.null(dims)) {
    dims_out <- paste0(dims, collapse = " x ")
    paste0("<", class(x)[[1]], "[", dims_out, "]>")
  } else {
    out <- format(x, trim = TRUE, justify = "none")
    out[is.na(x)] <- crayon_red(NA)

    out
  }
}

format_glimpse.character <- function(x, ...) {
  out <- encodeString(as.character(x), quote = '"')
  out[is.na(x)] <- crayon_red(NA)

  out
}

format_glimpse.factor <- function(x, ...) {
  if (any(grepl(",", levels(x), fixed = TRUE))) {
    out <- encodeString(as.character(x), quote = '"')
  } else {
    out <- format(x, trim = TRUE, justify = "none")
  }
  out[is.na(x)] <- crayon_red(NA)

  out
}