Skip to main content

Finding slices

Warning. This page is under construction.

head() and tail() take, respectively, the top few or the last few rows:

reformatted %>% head( n = 10 )
reformatted %>% tail( n = 10 )

slice_head() and slice_tail() do the same thing in groups:

reformatted %>% group_by( country ) %>% slice_head( n = 10 )
reformatted %>% group_by( country ) %>% slice_tail( n = 10 )

This gets particularly useful when you use arrange() to put things in order. To show this, let's try finding the years with the highest life expectancy for each country:

(
reformatted
%>% group_by( country )
%>% arrange( desc( life_expectancy , .by_group = TRUE )) # You need this .by_group!
%>% slice_head( n = 2 )
)

Finding a random sample

There is also slice_sample() which is useful to randomly sample rows. For example let's pick two random year by country:

(
reformatted
%>% group_by( country )
%>% slice_sample( n = 2 )
)
Question

What happens if you run this again - do you get the same answer?

Answer

No! You get a random sample.