Skip to content
Tags

,

A convenience function corner

2010/07/20

There are very convenient functions in R called head and tail. They return the first and the last part of an object respectively. Everything is fine until you happen to face a really big matrix or a data frame. If you have set a max.print option to some relatively small value (say 100), all you get using head or tail is a lump of column names. Otherwise the output is pretty heavy and the benefits of these functions are practically lost.
So I have struggled for some time using a command:

dataframename[a:b, c:d] 

The need to type this repeatedly started annoying me, so I proudly introduce a function I wrote myself to make my life a little bit more comfortable:

corner <- function(x, type = 1, n = 6L){
    if(!inherits(x, c("matrix", "data.frame"))) {
        stop("x should be a matrix or a data frame!")
    }
    n1 <- min(n, dim(x)[1])
    n2 <- min(n, dim(x)[2])
    marg <- vector("list", 4)
    marg[[1]] <- list(1:n1, 1:n2)
    marg[[2]] <- list((dim(x)[1] - n1 + 1):dim(x)[1], 1:n2)
    marg[[3]] <- list(1:n1, (dim(x)[2] - n2 + 1):dim(x)[2])
    marg[[4]] <- list((dim(x)[1] - n1 + 1):dim(x)[1],
                      (dim(x)[2] - n2 + 1):dim(x)[2])
    eval(x[marg[[type]][[1]], marg[[type]][[2]]])
}

Here x is the matrix or data frame to be printed, type is an integer, specifying which corner to print, with 1 meaning the upper left, 2 – lower left, 3 – upper right and 4 – lower right corners, and n gives the number of rows and columns to return.
type defaults to 1, since I print that corner most often, and n defaults to 6 – the value that head and tail use. This way, the usage becomes (with A being some matrix or a data frame):

corner(A) 

.

From → Experiments

Leave a Comment

Leave a comment