![]() |
R is a versatile language that is widely used in data analysis and statistical computing. A common task when working with data is removing one or more columns from a data frame. This guide will show you various methods to remove columns in R Programming Language using different approaches and providing examples to illustrate each method. Why Remove Columns?Removing columns from a data frame is a common task in data preprocessing and cleaning. It might be necessary to remove a column when.
Let’s explore the methods to remove a column in R. Using the Base R SyntaxIn Base R, you can remove columns using negative indexing or the subset function. To remove a column by name, you can use negative indexing.
Output: ID Name Age Gender
1 1 Ali 25 F
2 2 Boby 30 M
3 3 Charles 35 M
4 4 David 40 M
5 5 Eva 45 F
ID Name Gender
1 1 Ali F
2 2 Boby M
3 3 Charles M
4 4 David M
5 5 Eva F Subset FunctionThe subset function can also be used to remove columns.
Output: ID Name Age Gender
1 1 Ali 25 F
2 2 Boby 30 M
3 3 Charles 35 M
4 4 David 40 M
5 5 Eva 45 F
ID Name Age
1 1 Ali 25
2 2 Boby 30
3 3 Charles 35
4 4 David 40
5 5 Eva 45 Remove A Column Using dplyrThe dplyr package, part of the tidyverse, provides a convenient way to manipulate data frames. You can use the select function to remove columns.
Output: ID Name Age Gender
1 1 Ali 25 F
2 2 Boby 30 M
3 3 Charles 35 M
4 4 David 40 M
5 5 Eva 45 F
ID Name Gender
1 1 Ali F
2 2 Boby M
3 3 Charles M
4 4 David M
5 5 Eva F Remove Multiple ColumnsTo remove multiple columns, you can use dplyr::select with the c() function to specify the column names:
Output: ID Name Age Gender
1 1 Ali 25 F
2 2 Boby 30 M
3 3 Charles 35 M
4 4 David 40 M
5 5 Eva 45 F
ID Name
1 1 Ali
2 2 Boby
3 3 Charles
4 4 David
5 5 Eva Remove Columns by PatternYou can also remove columns based on a pattern in their names:
Output: ID Name Age Gender
1 1 Ali 25 F
2 2 Boby 30 M
3 3 Charles 35 M
4 4 David 40 M
5 5 Eva 45 F
ID Name
1 1 Ali
2 2 Boby
3 3 Charles
4 4 David
5 5 Eva ConclusionRemoving columns in R is a fundamental skill for data cleaning and manipulation. You can use various methods, including Base R syntax and the dplyr package, to remove columns by name, by position, or by pattern. Understanding these techniques allows you to manage your data frames effectively and focus on the columns that matter most for your analysis. |
Reffered: https://www.geeksforgeeks.org
R Language |
Related |
---|
![]() |
![]() |
![]() |
![]() |
![]() |
Type: | Geek |
Category: | Coding |
Sub Category: | Tutorial |
Uploaded by: | Admin |
Views: | 18 |