How to Extract Last Row in Data Frame in R


You can use the following methods to extract the last row in a data frame in R:

Method 1: Use Base R

last_row <- tail(df, n=1)

Method 2: Use dplyr

library(dplyr)

last_row <- df %>% slice(n())

Method 3: Use data.table

library(data.table)

last_row <- setDT(df[nrow(df), ])

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

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

#view data frame
df

  team points assists rebounds
1    A     99      33       30
2    B     90      28       28
3    C     86      31       24
4    D     88      39       24
5    E     95      34       28

Example 1: Extract Last Row Using Base R

The following code shows how to extract the last row of the data frame by using the tail() function from base R:

#extract last row in data frame
last_row <- tail(df, n=1)

#view last row
last_row

  team points assists rebounds
5    E     95      34       28

Using the tail() function, we’re able to extract only the last row in the data frame.

Note that you can change the value for the n argument to instead select the last n rows of the data frame.

Example 2: Extract Last Row Using dplyr

The following code shows how to extract the last row of the data frame by using the slice() function from the dplyr package:

library(dplyr)

#extract last row in data frame
last_row <- df %>% slice(n())

#view last row
last_row

  team points assists rebounds
1    E     95      34       28

Using the slice() function, we’re able to extract only the last row in the data frame.

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

Example 3: Extract Last Row Using data.table

The following code shows how to extract the last row of the data frame by using functions from the data.table package:

library(data.table)

#extract last row in data frame
last_row <- setDT(df[nrow(df), ])

#view last row
last_row

   team points assists rebounds
1:    E     95      34       28

Using the nrow() function, we’re able to extract only the last row in the data frame.

Additional Resources

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

How to Select Rows Where Value Appears in Any Column in R
How to Select Specific Columns in R
How to Select Columns by Index in R

Featured Posts

Leave a Reply

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