R Program to Drop Columns in a Dataframe

Example 1: Drop One Column From Dataframe in R

# Create a data frame
dataframe1 <- data.frame (
  Name = c("Juan", "Alcaraz", "Simantha"),
  Age = c(22, 15, 19),
  Vote = c(TRUE, FALSE, TRUE)
)

# drop third column
print(subset(dataframe1, select = -3))

Output

     Name Age
1     Juan  22
2  Alcaraz  15
3 Simantha  19

In the above example, we have used the subset() function to drop column of the dataframe named dataframe1.

subset(dataframe1, select = -3)

Here, inside subset(),

  • dataframe1 - a dataframe from which we want to drop a column
  • select = -3 - drops 3rd column i.e. Vote

If we passed select = 3 instead of select = -3, the function would return the 3rd column rather than dropping that column.


Example 2: Drop Multiple Column From Dataframe in R

We combine multiple columns with the c() function in the select parameter to drop multiple columns. For example,

# Create a data frame
dataframe1 <- data.frame (
  Name = c("Juan", "Alcaraz", "Simantha"),
  Age = c(22, 15, 19),
  Address = c("Nepal", "USA", "Germany"),
  Vote = c(TRUE, FALSE, TRUE)
)

# drop 2nd and 4th column
print(subset(dataframe1, select = - c(Age, Vote)))

Output

     Name Address
1     Juan   Nepal
2  Alcaraz     USA
3 Simantha Germany

In the above example, we have used the c() function and the subset() function to combine and drop multiple columns from dataframe1.

subset(dataframe1, select = - c(Age, Vote))

Here, select = - c(Age, Vote) selects two columns: Age and Vote and drops them from dataframe1.

Our premium learning platform, created with over a decade of experience and thousands of feedbacks.

Learn and improve your coding skills like never before.

Try Programiz PRO
  • Interactive Courses
  • Certificates
  • AI Help
  • 2000+ Challenges