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:
Please accept YouTube cookies to play this video. By accepting you will be accessing content from YouTube, a service provided by an external third party.
If you accept this notice, your choice will be saved and the page will refresh.
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.
- Subset Data Frame Rows by Logical Condition in R
- Sample Random Rows of Data Frame
- filter R Function of dplyr Package
- The dplyr Package in R
- R Functions List (+ Examples)
- The R Programming Language
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.
Statistics Globe Newsletter