Course
Data Frames
Convert a List to a DataframeCreate an Empty DataframeCombine Two Dataframe into OneChange Column Name of a DataframeExtract Columns From a DataframeDrop Columns in a DataframeReorder Columns in a DataframeSplit DataframeMerge Multiple DataframesDelete Rows From DataframeMake a List of DataframesIntroduction
"Hello World" ProgramAdd Two VectorsFind Sum, Mean and Product of Vector in R ProgrammingTake Input From UserGenerate Random Number from Standard DistributionsSample from a PopulationFind Minimum and MaximumSort a VectorStrings
Concatenate Two StringsFind the Length of a StringCheck if Characters are Present in a StringExtract n Characters From a StringReplace Characters in a StringCompare two StringsConvert Factors to CharactersTrim Leading and Trailing WhitespacesVectors
Concatenate a Vector of StringsCheck if a Vector Contains the Given ElementCount the Number of Elements in a VectorFind Index of an Element in a VectorAccess Values in a VectorAdd Leading Zeros to VectorR 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 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
.