How to Index Up to the End of Vectors & Data Frames in R (2 Examples)

This tutorial explains how to return the end of a vector or data frame in the R programming language.

Example 1: Extracting the End of a Vector

my_x <- LETTERS[1:7]            # Creating example data
my_x                            # Show vector in RStudio console
# "A" "B" "C" "D" "E" "F" "G"
my_x[- (1:4)]                   # Returning elements at the end
# "E" "F" "G"

Example 2: Extracting the End of a Data Frame

my_df <- data.frame(x = 1:7,    # Creating example data
                   y = letters[1:7],
                   z = 5)
my_df                           # Show data in RStudio console
#   x y z
# 1 1 a 5
# 2 2 b 5
# 3 3 c 5
# 4 4 d 5
# 5 5 e 5
# 6 6 f 5
# 7 7 g 5
tail(my_df, 4)                  # Returning bottom rows
#   x y z
# 4 4 d 5
# 5 5 e 5
# 6 6 f 5
# 7 7 g 5

Leave a Reply

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

Fill out this field
Fill out this field
Please enter a valid email address.
You need to agree with the terms to proceed

Menu
Top