# What is the best way to filter by row number in R?

**Data Science Tutorials**, and kindly contributed to R-bloggers]. (You can report issue about the content on this page here)

Want to share your content on R-bloggers? click here if you have a blog, or here if you don't.

The post What is the best way to filter by row number in R? appeared first on Data Science Tutorials

What is the best way to filter by row number in R?, The slice function from the dplyr package can be used to filter a data frame by row number using the following methods.

How to Count Distinct Values in R – Data Science Tutorials

**Method 1: Filter by Specific Row Numbers**

df %>% slice(2, 3, 8)

Rows 2, 3, and 8 will be returned as a result of this.

**Method 2: Filter by Range of Row Numbers**

df %>% slice(2:5)

Rows 2 through 5 will be returned as a result of this.

With the following data frame in R, the following examples explain how to utilize each method in practice.

How to perform the MANOVA test in R? – Data Science Tutorials

Let’s create a data frame

df <- data.frame(team=c('A', 'B', 'C', 'D', 'E', 'F', 'G', 'H'), points=c(110, 120, 80, 16, 105, 185, 112, 112), rebounds=c(18, 18, 14, 13, 12, 15, 17, 12))

Now we can view the data frame

df team points rebounds 1 A 110 18 2 B 120 18 3 C 80 14 4 D 16 13 5 E 105 12 6 F 185 15 7 G 112 17 8 H 112 12

## Example 1: Filter by Specific Row Numbers

To filter for rows 2, 3, and 8, we may use the following code.

Statistical test assumptions and requirements – Data Science Tutorials

library(dplyr)

Let’s filter for only rows 2, 3, and 8

df %>% slice(2, 3, 8) team points rebounds 1 B 120 18 2 C 80 14 3 H 112 12

From the original data frame, only rows 2, 3, and 8 are returned.

## Example 2: Filter by a row number range

To filter for rows between 2 and 5, we can use the following code.

Sorting in r: sort, order & rank R Functions – Data Science Tutorials

library(dplyr)

Now filter for rows between 2 and 5

df %>% slice(2:5) team points rebounds 1 B 120 18 2 C 80 14 3 D 16 13 4 E 105 12

Only rows 2 to 5 from the original data frame are returned.

The post What is the best way to filter by row number in R? appeared first on Data Science Tutorials

**leave a comment**for the author, please follow the link and comment on their blog:

**Data Science Tutorials**.

R-bloggers.com offers

**daily e-mail updates**about R news and tutorials about learning R and many other topics. Click here if you're looking to post or find an R/data-science job.

Want to share your content on R-bloggers? click here if you have a blog, or here if you don't.