slice R Function of dplyr Package (Example)

 

In this tutorial you’ll learn how to extract certain rows of a data set with the slice function of the dplyr package in the R programming language.

The article will contain these contents:

Let’s take a look at some R codes in action.

 

Creation of Example Data

In the example of this tutorial, I’ll use the following data frame in R:

data <- data.frame(x1 = 1:5,                    # Create example data
                   x2 = LETTERS[1:5],
                   x3 = 5)
data                                            # Print example data
#   x1 x2 x3
# 1  1  A  5
# 2  2  B  5
# 3  3  C  5
# 4  4  D  5
# 5  5  E  5

Our example data contains five rows and three columns. Note that we could also apply the following R code to a tibble instead of a data frame.

To be able to use the slice function, we have to install and load the dplyr package:

install.packages("dplyr")                       # Install dplyr
library("dplyr")                                # Load dplyr

 

Example: Application of slice Function

The slice function of the dplyr R package can be used to extract columns of a data frame or tibble as shown below:

slice(data, c(1, 3, 5))                         # Apply slice function
#   x1 x2 x3
# 1  1  A  5
# 2  3  C  5
# 3  5  E  5

Within the slice function, we had to specify the name of our input data and the row index of all rows we want to retain. In this example, we extracted the first, third, and fifth row of the example data.

 

Video, Further Resources & Summary

Have a look at the following video of my YouTube channel. In the video, I’m explaining the dplyr package and its functions in some more detail:

 

 

Furthermore, you might want to have a look at the other tutorials of this website. I have released several tutorials on the dplyr package and related functions already.

 

Summary: This tutorial explained how to choose rows by position with the dplyr package in R. Please let me know in the comments section below, in case you have additional questions or comments. Furthermore, please subscribe to my email newsletter in order to get updates on new articles.

 

Subscribe to the Statistics Globe Newsletter

Get regular updates on the latest tutorials, offers & news at Statistics Globe.
I hate spam & you may opt out anytime: Privacy Policy.


Leave a Reply

Your email address will not be published. Required fields are marked *

Fill out this field
Fill out this field
Please enter a valid email address.

Top