Skip to content

Instantly share code, notes, and snippets.

@pimentel
Last active June 27, 2018 03:09
Show Gist options
  • Save pimentel/256fc8c9b5191da63819 to your computer and use it in GitHub Desktop.
Save pimentel/256fc8c9b5191da63819 to your computer and use it in GitHub Desktop.
Slightly more sane head() for lists in R
catDf <- data.frame(meow = rnorm(100), purr = rpois(100, 3))
aList <- list(aVector = 1:20, aDf = catDf, anotherList = list(1:200, 1:20))
# annoying as hell, right?
head(aList)
#' Return the first or last part of a list
#'
#' Returns the first or last part of a list. Instead of returning the first
#' n entries as the standard head() does, it attempts to call head()
#' recursively on the entries in the list. If it fails, it will return the
#' particular entry (standard behavior).
#' @param obj a list object
#' @param n a single integer. If positive, prints the first n items for the
#' list and all entries in the list. If negative, prints all but the last
#' n items in the list.
#' @return a list of length n, with items in the list of length n
head.list <- function(obj, n = 6L, ...)
{
stopifnot(length(n) == 1L)
origN <- n
n <- if (n < 0L)
max(length(obj) + n, 0L)
else min(n, length(obj))
lapply(obj[seq_len(n)], function(x)
{
tryCatch({
head(x, origN, ...)
}, error = function(e) {
x
})
})
}
environment(head.list) <- asNamespace('utils')
# less annoying behavior!
head(aList)
@elisehellwig
Copy link

This is so awesome!

@petermeissner
Copy link

nice

@dfalster
Copy link

Nice, thanks!

@jjmmii
Copy link

jjmmii commented Jan 10, 2018

Thanks so much!

@botamochi6277
Copy link

Awesome!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment