R – Deselecting a column by name

dataframeindexingrslice

Is there a way to select all columns of a data frame except a column that has a particular name.

It would be the analog of df[, -1], except using the column name instead of the index?

Best Solution

You can do this using vector subsetting. First, create a dummy data set:

R> dd = data.frame(A = 1:3, B = 1:3, C=1:3, D=1:3)

Then use the ! operator to reverse the selection:

R> dd[ ,!(colnames(dd) == "A")]

  B C D
1 1 1 1
2 2 2 2
3 3 3 3

Alternatively, you could have:

  • A slightly shorter version (courtesy of @Tomas):

    dd[ , names(dd) != "A"]
    
  • To cope with multiple columns (courtesy of @Tyler)

    dd[ ,!(colnames(dd) %in% c("A", "B"))]