Slice

In this lesson, we will explore the slice function. This topic should be quite straightforward and easy to grasp, making this a short and simple lesson.

The slice function can be viewed as an extension of the head and tail functions, capable of behaving like either of them based on the inputs it receives. Essentially, it subsets a dataframe to include only the specified row numbers.

Let's demonstrate its use by creating a subset that retains only the first row:

Next only the second row:

And finally the first through third rows:

Slice after group_by

Pretty simple so far right! The slice function becomes particularly useful when we want to subset data following a group-by operation. In our next example, we will retain the first two observations for each Species.

In our last example, lets employ the function n, which counts the number of rows in either a grouped or full dataframe, to grab the final observation within each Species.

Practice exercise

Use group_by and slice to keep the second and third row of each species.