2

Is this the correct way to delete a column from a dataframe in R? Or there is a better way?

dataframe$column <- NULL
Nymeria123
  • 51
  • 2
  • 8
  • 7
    It's a robust way. `dataframe[["column"]] <- NULL` is _slightly_ more robust because it doesn't do partial matching, but that's rarely an issue. – alistaire Jan 13 '19 at 06:00
  • 3
    It might be worth/interesting to also take a look at this post: [Remove an entire column from a data.frame in R](https://stackoverflow.com/questions/6286313/remove-an-entire-column-from-a-data-frame-in-r) – Maurits Evers Jan 13 '19 at 06:10
  • Thanks alistaire and Maurits Evers :) – Nymeria123 Jan 14 '19 at 03:55

2 Answers2

0

Another way is by using negative subscripts:

Say, you want to remove column #2 from the data frame:

 df <- df[,-2]

If you want to remove several columns, use c; for example:

 df <- df[,-c(2, 5, 7:10)]
Chris Ruehlemann
  • 20,321
  • 4
  • 12
  • 34
0

using dplyr from tidyverse you can pipe in the ability to drop a single or multiple columns:

library(tidyverse)

dataframe <- dataframe %>%
  select(-column)
nycrefugee
  • 1,629
  • 1
  • 10
  • 23