Skip to content

Instantly share code, notes, and snippets.

@WillForan
Created January 16, 2024 01:48
Show Gist options
  • Save WillForan/af3ebe13eaa17f2316dd732c82689565 to your computer and use it in GitHub Desktop.
Save WillForan/af3ebe13eaa17f2316dd732c82689565 to your computer and use it in GitHub Desktop.
#' bighead - show subset in each dimension
#' @description like head but in all dimensions
#' @param obj - indexable object: vector, data.frame, matrix, or array
#' @param ntotal - total maximum elements to show
bighead <- function(obj, ntotal=100){
# dimension of object (dataframe = 2D)
dims <- dim(obj)
# vectors has NULL dim. Special case: set dim to length
if(is.null(dims)) dims <- c(length(obj))
ndim <- length(dims)
# use ndim root of ntotal to limit each dimension
# TODO: will be 0 if obj has a lot of dimensions ... that's no good
n_per_dim <- floor(ntotal^(1/ndim))
# along each dim: first to ndim-th root item (or total length of dim if smaller)
idx <- lapply(dims, \(i) c(1:(min(i, n_per_dim))))
# TODO: could be smarter
# currently always returns less than or equal to total items requested
# if one dim is less than what's asked, could show more in other dims
do.call(\(...) obj[...], idx)
}
bighead_test <- function(){
testthat::expect_equal(bighead(1:100,27),1:27)
testthat::expect_equal(bighead(array(1:27,c(3,3,3)),9),
array(c(1:2,4:5,10:11,13:14),c(2,2,2)))
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment