1

Possible Duplicate:
Drop Columns R Data frame

Assuming a matrix with 3 named columns "A", "B", C", I can unselect columns "B" and "C" like this:

df[, -c(2, 3)]

But what if I want to use column names? How can I df[, -c("B", "C")]?

Community
  • 1
  • 1
Robert Kubrick
  • 7,491
  • 11
  • 51
  • 85

1 Answers1

3

Matching is your friend:

R> DF <- data.frame(A=1:2, B=2:3, C=3:4)
R> DF[, !(colnames(DF) %in% c("B","C")), drop=FALSE]
  A
1 1
2 2
R> 

The key is that you need boolean vectors for indexing (or else, numeric indices). So any expression creating booleans will do.

Dirk Eddelbuettel
  • 331,520
  • 51
  • 596
  • 675