How to Select First N Rows of Data Frame in R (3 Examples)


You can use one of the following methods to select the first N rows of a data frame in R:

Method 1: Use head() from Base R

head(df, 3)

Method 2: Use indexing from Base R

df[1:3, ]

Method 3: Use slice() from dplyr

library(dplyr)

df %>% slice(1:3)

The following examples show how to use each method in practice with the following data frame:

#create data frame
df <- data.frame(team=c('A', 'B', 'C', 'D', 'E', 'F', 'G'),
                 points=c(99, 90, 86, 88, 95, 99, 91),
                 assists=c(33, 28, 31, 39, 34, 35, 40))

#view data frame
df

  team points assists
1    A     99      33
2    B     90      28
3    C     86      31
4    D     88      39
5    E     95      34
6    F     99      35
7    G     91      40

Example 1: Use head() from Base R

One way to select the first N rows of a data frame is by using the head() function from base R:

#select first 3 rows of data frame
head(df, 3)

  team points assists
1    A     99      33
2    B     90      28
3    C     86      31

If you use the head() function without any numerical argument, R will automatically select the first 6 rows of the data frame:

#select first 6 rows of data frame
head(df)

  team points assists
1    A     99      33
2    B     90      28
3    C     86      31
4    D     88      39
5    E     95      34
6    F     99      35

Example 2: Use indexing from Base R

Another way to select the first N rows of a data frame is by using indexing syntax from base R:

#select first 3 rows of data frame
df[1:3, ]

  team points assists
1    A     99      33
2    B     90      28
3    C     86      31

You can also use this syntax to only select the first N rows of a specific column:

#select first 3 rows of 'team' and 'points' columns only
df[1:3, c('team', 'points')]

  team points
1    A     99
2    B     90
3    C     86

Example 3: Use slice() from dplyr

Another way to select the first N rows of a data frame is by using the slice() function from the dplyr package:

library(dplyr)

#select first 3 rows of data frame
df %>% slice(1:3)

  team points assists
1    A     99      33
2    B     90      28
3    C     86      31

Related: How to Use the slice() Function in dplyr (With Examples)

Additional Resources

The following tutorials explain how to perform other common tasks in R:

How to Append Rows to a Data Frame in R
How to Remove Duplicate Rows in R
How to Sum Specific Rows in R

Leave a Reply

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