19

Possible Duplicate:
removing specific rows from a dataframe

Let's say I have a data frame consisting of a number of rows, like this:

X <- data.frame(Variable1=c(11,14,12,15),Variable2=c(2,3,1,4))

Variable1    Variable2
11           2
14           3
12           1
15           4

Now, let's say that I want to create a new data frame that is a duplicate of this one, only that I'm removing all rows in which Variable1 has a certain numerical value. Let's say we have these numbers stored in a vector, v.

That is, if v contains the numbers 11 and 12, the new data frame should look like this:

Variable1    Variable2
14           3
15           4

I've been searching the net for quite some time now trying to figure out how to do something like this. Mainly, I would just need some kind of command saying removeRow(dataframe, row) or something like that.

Community
  • 1
  • 1
Speldosa
  • 1,900
  • 5
  • 21
  • 36
  • 9
    Have you searched SO for this question? The answer surely involves using %in% and the extraction operator "[" but I will lay odds its already been answered. For instance the first one that comes up with a search using your question title: http://stackoverflow.com/questions/7112872/removing-specific-rows-from-a-dataframe – IRTFM Nov 23 '11 at 14:51
  • 4
    This is a fairly common R practice. Here's a hint, instead of trying to remove the rows you don't want, try to make a new data frame containing the rows that you do want. – Chris Nov 23 '11 at 14:54
  • You should post a reproducible example. `dput` is your friend! – Zach Nov 23 '11 at 14:57

1 Answers1

66
 X <- data.frame(Variable1=c(11,14,12,15),Variable2=c(2,3,1,4))
> X
  Variable1 Variable2
1        11         2
2        14         3
3        12         1
4        15         4
> X[X$Variable1!=11 & X$Variable1!=12, ]
  Variable1 Variable2
2        14         3
4        15         4
> X[ ! X$Variable1 %in% c(11,12), ]
  Variable1 Variable2
2        14         3
4        15         4

You can functionalize this however you like.

Zach
  • 29,791
  • 35
  • 142
  • 201