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 columnselect = -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
.