Skip to content

Instantly share code, notes, and snippets.

@bhive01
Created July 27, 2017 20:31
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save bhive01/643d32bc13d3a55f9ac371ab3c832c96 to your computer and use it in GitHub Desktop.
Save bhive01/643d32bc13d3a55f9ac371ab3c832c96 to your computer and use it in GitHub Desktop.
torso <- function(d, n=5L, ...) {
stopifnot(length(n) == 1L)
center <- as.integer(nrow(d)/2)
left <- as.integer(center-n/3)
right <- as.integer(center + n/3)
d[seq.int(from= left, to = right, by = 1L),]
}
topntail <- function(d, n=4L) {
rbind(head(d,n), tail(d,n))
}
vet <- function(d, n=4L) {
rbind(head(d,n), torso(d,n), tail(d,n))
}
torso(iris)
topntail(iris)
vet(iris)
@rossholmberg
Copy link

Nice idea. This might work a little better for the torso function:

torso <- function(d, n=5L) {
    stopifnot(length(n) == 1L)
    center <- as.integer(nrow(d)/2)
    left <- as.integer(center - n/2)
    d[ seq_len(n) + left - 1L, ]
}

Using seq_len negates the need for calculating right, and ensures you'll always get the right number of rows (notice how torso(iris,5) currently give 4 rows instead of the 5 requested). Also n/2 seems more appropriate for calculating left than n/3. Was there a reason for the 3 there?

In fact, depending on your taste, it might be worth simplifying a little more by skipping the center assignment too:

torso <- function(d, n=5L) {
    stopifnot(length(n) == 1L)
    left <- as.integer(nrow(d)/2 - n/2)
    d[ seq_len(n) + left - 1L, ]
}

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