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")]?

1
  • Agree it is duplicate. Comment: The -grep() strategy is more general. Commented Jan 5, 2012 at 18:03

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

3 Comments

Thanks, a lot more complicate than the - operator though :(
So just define a new '-' (alike) operator or function.
Good suggestion but then I'm not clear why it's not already defined. Why only for indexes? After all I can still use the column names to select columns: DF[, c("A", "B")]

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.