r-lib / err

Ideas for error handling tools
1 stars 2 forks source link

Helper to truncate vectors #2

Open hadley opened 6 years ago

hadley commented 6 years ago
vec_trunc <- function(x, n = 10) {
  if (length(x) <= n) {
    return(x)
  }

  c(x[seq_len(n)], paste0("and ", big_mark(length(x) - n), " more"))
}

big_mark <- function (x, ...) {
  mark <- if (identical(getOption("OutDec"), ",")) "." else ","
  formatC(x, big.mark = mark, ...)
}

vec_trunc(letters)
zeehio commented 5 years ago

Sorry for stepping in, feel free to ignore the idea if you are not interested.

There is a "nicer to the user" implementation (in my opinion at least) of the truncation function that avoids the "and 1 more" wording (e.g. on a vector of length 11 in the example above):

vec_trunc <- function(x, n = 10, m = n + 5) {
  if (length(x) <= m) {
    return(x)
  }

  c(x[seq_len(n)], paste0("and ", big_mark(length(x) - n), " more"))
}

With this implementation vectors up to length 15 would be printed in full, but if the vector is longer then only the first 10 elements are printed.

The reasoning behind this is that users often want to see all the elements if there are few of them. If there are many elements then printing a small number is usually enough to get an idea of the global problem and not clobber the screen with them.

Thanks for your splendid work!