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

In R, the first N rows of a data frame can be selected using the head() function, which takes the number of rows as an argument and returns the first N rows of the data frame. For example, head(df,3) will return the first 3 rows of df. Additionally, if you want to select a subset of rows from a data frame, you can use the subset() function, which takes a logical expression as an argument and returns a subset of the data frame based on the expression. Finally, you can also use the slice() function to select a range of rows from a data frame, by specifying the start and end rows as arguments.


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

#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 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:

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

x