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 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
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.
Please accept YouTube cookies to play this video. By accepting you will be accessing content from YouTube, a service provided by an external third party.
If you accept this notice, your choice will be saved and the page will refresh.
In addition, you may want to have a look at the other tutorials of Statistics Globe:
- Select Data Frame Column Using Character Vector
- Select Data Frame Rows where Column Values are in Range
- R Programming Overview
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.
Statistics Globe Newsletter