combining head and tail methods in R

r head specific columns
tails in r
print the first and the last six rows using head and tail functions
opposite of tail r
r head list
head and tail rstudio
tail sort in r
how to extract first 2 rows in r

I use the head(d) and tail(d) methods in R package utils a lot - frequently one after the other. So I wrote a simple wrapper for the two functions:

    ht <- function(d, m=5, n=m){
      # print the head and tail together
      cat(" head -->  ", head(d,m), "\n", "--------", "\n", "tail -->  ", tail(d,n), "\n")
    }

And I got some unexpected results. Can someone please help me understand why? (so i can fix it or at least understand your solution!).

Some background...

Numeric values work fine:

x <- 1:100
ht(x)

So does complex:

ni <- as.complex(1:100)
ht(ni)

and characters:

ll <- letters[1:26]
ht(ll)

Matrix loses it's structure, returning [1,1] to [5,5] + [16,1] to [20,5] but as two vectors -- compare:

m <- matrix(1:10, 20)
ht(m)

to:

head(m, 5)
tail(m,5)

I would like to keep the matrix structure, as the utils methods does - is this possible?

Finally (well, there may be more bugs, this is just where I'm up to) data.frames are a mess:

df <- data.frame(num=x[1:26], char=ll)
ht(df)

This yields the following error:

head -->   Error in cat(list(...), file, sep, fill, labels, append) :   
  argument 2 (type 'list') cannot be handled by 'cat'

Steps so far:

As the utils method keeps the matrix tidy when done in bits, I tried to fix the problem with the following edit:

function(d, m=5, n=m){
  # print the head and tail together
  rb <- rbind(head(d, m), tail(d,n))
  if (class(d) == 'matrix'){
    len <- nrow(rb)
    cat(" head -->  ", rb[(1:m),], "\n", "--------", "\n", "tail -->  ", rb[((len-n):len),], "\n")
  }
  else cat(" head -->  ", rb[1,], "\n", "--------", "\n", "tail -->  ", rb[2,], "\n")
}

Which does not seem to have done anything to the matrix and still breaks with the same error when I use:

ht(df)

I am guessing from the errors that there is some issue with cat() here, but I cannot figure out what it is or how to fix it.

Can anyone please help?

Why not modify your function to output a list instead?

ht <- function(d, m=5, n=m){
  # print the head and tail together
  list(HEAD = head(d,m), TAIL = tail(d,n))
}

Here's the output for your matrix and data.frame:

ht(matrix(1:10, 20))
# $HEAD
#      [,1]
# [1,]    1
# [2,]    2
# [3,]    3
# [4,]    4
# [5,]    5
# 
# $TAIL
#       [,1]
# [16,]    6
# [17,]    7
# [18,]    8
# [19,]    9
# [20,]   10

ht(data.frame(num=x[1:26], char=ll))
# $HEAD
#   num char
# 1   1    a
# 2   2    b
# 3   3    c
# 4   4    d
# 5   5    e
# 
# $TAIL
#    num char
# 22  22    v
# 23  23    w
# 24  24    x
# 25  25    y
# 26  26    z

Combine calls to head and tail, Combine calls to head and tail. Description. A quick way to show the first and last n lines of a data.frame, matrix, or a text object. Just a pretty call to head and tail� In This tutorial we will learn about head and tail function in R. head() function in R takes argument “n” and returns the first n rows of a dataframe or matrix, by default it returns first 6 rows. tail() function in R returns last n rows of a dataframe or matrix, by default it returns last 6 rows. we can also use slice() group of functions in dplyr package like slice_sample(),slice_head

It was suggested I turn my comment into an answer.

In your R console, when you type head(m, 5), what you see printed on your screen is really the result of print(head(m, 5)). So if this is what you want your output to look like, consider using the print function rather than cat when displaying the head and tail of your objects:

ht <- function(d, m=5, n=m) {
  # print the head and tail together
  cat("head -->\n")
  print(head(d,m))
  cat("--------\n")
  cat("tail -->\n")
  print(tail(d,n))
}

m <- matrix(1:10, 20)
ht(m)
# head -->
#      [,1]
# [1,]    1
# [2,]    2
# [3,]    3
# [4,]    4
# [5,]    5
# --------
# tail -->
#       [,1]
# [16,]    6
# [17,]    7
# [18,]    8
# [19,]    9
# [20,]   10

I find @mrdwab's answer to be a very elegant solution. It does not explicitly use print, instead returns a list. However, when his function is called from the R console and the output is not assigned to anything, then it is printed to the console (hence print is used implicitly). I hope that helps you understand what's going on.

headtail function, show head and tail of an object with one command. Details. Tries to find good methods of combining the two results according to codeclass(x). Combine calls to head and tail Description. A quick way to show the first and last n lines of a data.frame, matrix, or a text object. Just a pretty call to head and tail or View

If you're already coding using the tidyverse principles and use the %>% (pipe) operator it is actually very easy to have just a one-liner:

library(magrittr)

your_dataframe %>% {
rbind(head(., 8), tail(., 8)
} %>% 
nrow()

# [1] 16

That basically uses rbind to merge the top head() and bottom tail() of the your_dataframe. The {} are used for calling lambda expressions (more info here). The . inside the head and tail means "Standard input" (your_dataframe).

head function, Since head() and tail() are generic functions, they may also have been extended tail(x, …) # S3 method for default tail(x, n = 6L, …) # S3 method for data.frame� If I have a file name myownfile.txt which contains 3 lines of text. foo hello world bar I want to display the line in the middle which is hello world by using head and tail command only.

Combining Head and Tail Commands : RStudio, Combining Head and Tail Commands. I am new to R and am trying to create a dataframe that takes the first three and last three rows of an already established� For matrices, 2-dim tables and data frames, head() (tail()) returns the first (last) n rows when n >= 0 or all but the last (first) n rows when n < 0. head.matrix() and tail.matrix() are exported. For functions, the lines of the deparsed function are returned as character strings.

Data wrangling in R, Great resources include RStudio's data wrangling cheatsheet (screenshots one, not column two str(gap_long) head(gap_long) tail(gap_long). Methods for calculating a Resultant Vector. The head to tail method to calculate a resultant which involves lining up the head of the one vector with the tail of the other. The parallelogram method to calculate resultant vector. This method involves properties of parallelograms but, in the end, boils down to a simple formula.

15 Easy Solutions To Your Data Frame Problems In R, Discover how to create a data frame in R, change column and row names, Next , you just combine the vectors that you made with the data.frame() function: lines of writers_df , you can use the head() and tail() funtions, respectively. In the end, with this method of accessing the values, you just create a� Details. For vector/array based objects, head() (tail()) returns a subset of the same dimensionality as x, usually of the same class.For historical reasons, by default they select the first (last) 6 indices in the first dimension ("rows") or along the length of a non-dimensioned vector, and the full extent (all indices) in any remaining dimensions.

Comments
  • In your R console, when you type head(m, 5), it is showing you the same result as would print(head(m, 5)). So consider using print instead of cat if that's how you want your result to look like.
  • flodel's is the answer. Intermix your cat functions that output annotation with print functions to show the objects. @flodel, put that as an answer.
  • No reason not to - i just hadn't realised it was necessary. In the case that ncols is 1 do you think it is best to unclass and treat as a vector? Or best to keep the list form?
  • @ricardo, what are you planning to do with the output? Is it being used interactively to just get some information about your data? Are you saving the output? Generally, though, I would say that if you want an accurate representation of your data, just keep it in the list form.
  • i was just planning on using it at the terminal - and i was keen to use cat only as therefore it would return a NULL ... so i could not get into trouble with assignment if i 'forgot'.
  • mrdwab, after some experimentation, i decided that a return value was not the worst thing in the world ... it could well be useful. I've amended you code so that the output relates to the inputs, so one can see what's gone on if you 'forget'. i think that solves my concern. Thus, it is now: function(d, m=5, n=m){ # print the head and tail together list <- NULL list[[paste0('HEAD #', m)]] <- head(d,m) list[[paste0('TAIL #', n)]] <- tail(d,n) return(list) }
  • +1. @mrdwab: i went with your solution - i've cribbed it for a blog post here. I linked back to this answer - just FYI.
  • Thanks, that helps a lot. I note that head and tail in utils have methods for ftable, table and function - will this approach handle all these cases also? (i am afk, so cannot check just now - but wanted to comment to say thankyou for explaining).
  • Yes, anything for which there are both head and tail methods.