Select Second to Last Columns of Data Frame in R (2 Examples)

 

In this tutorial, I’ll show how to remove the first column of a data frame in the R programming language.

Table of contents:

Let’s take a look at some R codes in action!

 

Creation of Example Data

The following data is used as basement for this R tutorial:

data <- data.frame(x1 = paste0("ID", 1:6),    # Create example data frame
                   x2 = letters[8:3],
                   x3 = "x",
                   x4 = 2:7,
                   x5 = LETTERS[10:15])
data                                          # Print example data frame

 

table 1 data frame select second last columns data frame r

 

Table 1 shows the structure of our exemplifying data – It consists of six rows and five columns.

 

Example 1: Remove First Variable of Data Frame Using Square Brackets & Negative Index Position

In this section, I’ll illustrate how to select the columns two to the last column using square brackets to subset our data frame.

Have a look at the following R code:

data_new1 <- data[ , - 1]                     # Remove first column
data_new1                                     # Print updated data frame

 

table 2 data frame select second last columns data frame r

 

By executing the previous R syntax we have created Table 2, i.e. a data frame containing the second to the last column of our input data frame.

 

Example 2: Remove First Variable of Data Frame Using ncol() Function

In Example 2, I’ll explain an alternative to the R code of Example 1 that is based on the ncol function.

We can extract the second to the last columns of our data frame using the ncol function as shown below:

data_new2 <- data[ , 2:ncol(data)]            # Remove first column
data_new2                                     # Print updated data frame

 

table 3 data frame select second last columns data frame r

 

As shown in Table 3, the previous syntax has created exactly the same data frame subset as the previous example. Whether you prefer to use square brackets and index positions or the ncol function is a matter of taste.

 

Video, Further Resources & Summary

Have a look at the following video of my YouTube channel. I’m illustrating the R code of this article in the video.

 

 

Additionally, you might have a look at the related articles on this website:

 

To summarize: In this article, I have illustrated how to delete the first variable of a data frame and filter only the remaining columns in the R programming language. If you have further questions, let me know in the comments section below.

 

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.

Top