Select Last Column of Data Frame in R (2 Examples)


In this article, I’ll explain how to extract the very last variable of a data frame in the R programming language.

Table of contents:

Let’s just jump right in:


Creation of Example Data

We use the following data as basement for this tutorial:

data <- data.frame(x1 = letters[9:3],             # Create example data frame
                   x2 = 2:8,
                   x3 = "l",
                   x4 = LETTERS[1:7])
data                                              # Print example data frame


table 1 data frame select last column data frame r


Table 1 shows that our exemplifying data contains seven rows and four columns.


Example 1: Extract Last Variable as Vector Object

In this example, I’ll explain how to refer to the last variable of a data frame using the ncol function in R.

Consider the following R code:

last_vec <- data[ , ncol(data)]                   # Apply ncol function
last_vec                                          # Print last column as vector
# [1] "A" "B" "C" "D" "E" "F" "G"

As you can see in the RStudio console, we have created a new vector object containing the values of our last data frame column.

Did you want to convert the last column to a vector? Fine! If not, keep on reading.


Example 2: Extract Last Variable as Data Frame

In Example 2, I’ll illustrate how to select the last column of a data frame and keep it in a single column data frame.

For this, we have to specify the drop argument to be equal to FALSE:

last_data <- data[ , ncol(data), drop = FALSE]    # Apply ncol & drop
last_data                                         # Print last column as data frame


table 2 data frame select last column data frame r


As shown in Table 2, the previous R syntax has created a data frame object consisting of the values of the column at the very end of our input data frame.


Video & Further Resources

In case you need more info on the R code of this article, you might have a look at the following video that I have published on my YouTube channel. I illustrate the examples of this article in the video.



In addition, you may want to have a look at the other tutorials of Statistics Globe:


To summarize: You have learned in this tutorial how to select and filter the last data frame column in R. Please tell me about it in the comments section, in case you have additional questions.


Subscribe to the Statistics Globe Newsletter

Get regular updates on the latest tutorials, offers & news at Statistics Globe.
I hate spam & you may opt out anytime: Privacy Policy.

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.