1
df <- data.frame(vin, make, model, year, category)

I would like to delete/remove columns, "year" and "category", and put them in a new view

akrun
  • 874,273
  • 37
  • 540
  • 662
Garrick Brim
  • 87
  • 1
  • 3
  • 9

1 Answers1

1

We can use setdiff to get all the columns except the 'year' and 'category'.

 df1 <- df[setdiff(colnames(df), c('year', 'category'))]
 df1
 #  vin make model
 #1   1    A     D
 #2   2    B     E
 #3   3    C     F

Including the comments from @Frank and @Ben Bolker.

We can assign the columns to NULL

  df$year <- NULL
  df$category <- NULL

Or use subset from base R or select from dplyr

  subset(df, select=-c(year, category))
  library(dplyr)
  select(df, -year, -category)

data

df <- data.frame(vin=1:3, make=LETTERS[1:3], model=LETTERS[4:6],
           year=1991:1993, category= paste0('GR', 1:3))
Community
  • 1
  • 1
akrun
  • 874,273
  • 37
  • 540
  • 662
  • 2
    Assigning NULL to each also works, I guess because data.frames are lists of (pointers to) vectors: `df$year <- NULL; df$category <- NULL` – Frank Aug 12 '15 at 20:50
  • 2
    or, conveniently (with the known [caveats about using subset()](http://stackoverflow.com/questions/9860090/in-r-why-is-better-than-subset)), use `subset(df,select=-c(year,category))` or `dplyr::select(df,-c(year,category))` – Ben Bolker Aug 12 '15 at 20:52