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.