Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Remove multiple columns from a df

I have a dataframe and I wish to remove 2 columns from it using the names, following another post on here it suggests the following code should work (or be close to working), would anyone be able to point me in the right direction here.

My df column dames

head(economics_df)

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

  `Series Name`  `Series Code` Country `Country Code` `1997` `1998` `1999` `2000` `2001` `2002` `2003` `2004` `2005` `2006` `2007` `2008` `2009` `2010` `2011` `2012`
  1 GDP (current … NY.GDP.MKTP.… Spain   ESP            5.900… 6.192… 6.349… 5.983… 6.278… 7.087… 9.074… 1.069… 1.153… 1.260…

code to remove unwanted columns

economics_df = economics_df %>% select(-c(`Series Code`, `Country Code`))

other ways tried

economics_df = economics_df[-c("`Series Code`", "`Country Code`")]

>Solution :

Would this work? It’s hard to know without the structure of the column names.

library(dplyr)

economics_df = economics_df %>% 
  dplyr::select(-c("`Series Code`", "`Country Code`"))

Or using base R:

economics_df = df[, !names(df) %in% c("`Series Code`", "`Country Code`")]

Output

  `Series Name` `Country` `1997`
1             1         1      1

Data

economics_df <- structure(list(``Series Name`` = 1, ``Series Code`` = 1, ``Country`` = 1, 
    ``Country Code`` = 1, ``1997`` = 1), class = "data.frame", row.names = c(NA, 
-1L))

#  `Series Name` `Series Code` `Country` `Country Code` `1997`
#1             1             1         1              1      1

OR (if you’re column names are structured slightly different), then remove the outer quotation marks:

economics_df = economics_df %>% 
  dplyr::select(-c(`Series Code`, `Country Code`))

economics_df = economics_df[, !names(economics_df) %in% c(`Series Code`, `Country Code`)]

Output

economics_df <- structure(list(`Series Name` = "1", `Series Code` = 1, Country = "1", 
    `Country Code` = 1, `1997` = 1), row.names = c(NA, -1L), class = "data.frame")
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading