15.1 C
London
Friday, July 5, 2024
HomeStatistics TutorialRHow to Delete Multiple Columns in R (With Examples)

How to Delete Multiple Columns in R (With Examples)

Related stories

Learn About Opening an Automobile Repair Shop in India

Starting a car repair shop is quite a good...

Unlocking the Power: Embracing the Benefits of Tax-Free Investing

  Unlocking the Power: Embracing the Benefits of Tax-Free Investing For...

Income Splitting in Canada for 2023

  Income Splitting in Canada for 2023 The federal government’s expanded...

Can I Deduct Home Office Expenses on my Tax Return 2023?

Can I Deduct Home Office Expenses on my Tax...

Canadian Tax – Personal Tax Deadline 2022

  Canadian Tax – Personal Tax Deadline 2022 Resources and Tools...

Often you may want to delete multiple columns at once from a data frame in R.

The easiest way to do this is with the following syntax:

df[ , c('column_name1', 'column_name2')] 

For example, the following syntax shows how to delete columns 2 and 3 from a given data frame:

#create data frame
df #delete columns 2 and 3 from data frame
df[ , c('var2', 'var3')] #view data frame
df

  var1 var4
1    1    1
2    3    1
3    2    2
4    9    8
5    5    7

We can also delete columns according to their index:

#create data frame
df #delete columns in position 2 and 3
df[ , c(2, 3)] #view data frame
df

  var1 var4
1    1    1
2    3    1
3    2    2
4    9    8
5    5    7

And we can use the following syntax to delete all columns in a range:

#create data frame
df #delete columns in range 1 through 3
df[ , 1:3] #view data frame
df

  var4
1    1
2    1
3    2
4    8
5    7

In general it’s recommended to delete columns by their name rather than their position simply because if you add or reorder columns then the positions could change.

By using column names, you ensure that you delete the correct columns regardless of their position.

Additional Resources

How to Loop Through Column Names in R
How to Combine Two Columns into One in R
How to Remove Outliers from Multiple Columns in R

Subscribe

- Never miss a story with notifications

- Gain full access to our premium content

- Browse free from up to 5 devices at once

Latest stories