List All Column Names But One in R (2 Examples)
This tutorial illustrates how to get a list of all variable names except one in the R programming language.
The tutorial contains this content:
You’re here for the answer, so let’s get straight to the examples…
Creation of Example Data
Have a look at the example data below:
data <- data.frame(x1 = 4:7, # Create example data x2 = "X", x3 = letters[1:4]) data # Print example data # x1 x2 x3 # 1 4 X a # 2 5 X b # 3 6 X c # 4 7 X d
The previous output of the RStudio console shows that our example data has four rows and three columns. The variables of our data frame are called x1, x2, and x3.
Example 1: Create List Containing All Column Names But One
In this section, I’ll illustrate how to construct a vector of variable names that contains all names except one. For this, we can use the colnames function as shown below:
list_names <- colnames(data)[colnames(data) != "x2"] # Get names list_names # Print names # "x1" "x3"
Have a look at the previous output of the RStudio console: It shows all column names of our data frame except “x2”.
Example 2: Remove Data Frame Column Using List of Names
In Example 2, I’ll show how to use the list of names that we have created in Example 1 to drop a certain column of our data matrix.
Have a look at the following R code:
data_new <- data[ , list_names] # Drop column data_new # Print new data frame # x1 x3 # 1 4 a # 2 5 b # 3 6 c # 4 7 d
As you can see, we have created a new data frame that consists of all variables but the column x2.
Video & Further Resources
Would you like to learn more about data frames and column names? Then you could have a look at the following video of my YouTube channel. In the video, I’m explaining the R programming code of this tutorial:
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.
Furthermore, I can recommend to read the related tutorials on this website. You can find some tutorials about topics such as lists, extracting data, and variables below:
- Create Data Frame where a Column is a List
- Sort Variables of Data Frame by Column Names
- Convert Values in Column into Row Names of Data Frame
- Select Rows if Value in One Column is Smaller Than in Another(Examples)
- R Programming Language
Summary: In this article you learned how to return a vector of variable names in R. If you have additional comments and/or questions, please let me know in the comments.