Skip to content
Prev 393622 / 398503 Next

Removing variables from data frame with a wile card

I am new to this thread. At the risk of presenting something that has been shown before, below I demonstrate how a column in a data frame can be dropped using a wild card, i.e. a column whose name starts with "th" using nothing more than base r functions and base R syntax. While additions to R such as tidyverse can be very helpful, many things that they do can be accomplished simply using base R.  

# Create data frame with three columns
one <- rep(1,10)
one
two <- rep(2,10)
two
three <- rep(3,10)
three
mydata <- data.frame(one=one, two=two, three=three)
cat("Data frame with three columns\n")
mydata

# Drop the column whose name starts with th, i.e. column three
# Find the location of the column
ColumToDelete <- grep("th",colnames((mydata)))
cat("The colomumn to be dropped is the column called three, which is column",ColumToDelete,"\n")
ColumToDelete

# Drop the column whose name starts with "th"
newdata2 <- mydata[,-ColumnToDelete]
cat("Data frame after droping column whose name is three\n")
newdata2

I hope this helps.
John