Skip to content
Prev 142997 / 398500 Next

data.frame indexing

On Apr 28, 2008, at 10:40 AM, Georg Ehret wrote:

            
Hi,

I think one of the most wonderfully magic things about R is that it  
can use a logical array to index other things (like a data frame).   
You could use the extra step with which, but in your case you can  
bypass that step.  Here is a simple example...

 > a <- data.frame(V1 = seq(-5,5), V2 = seq(-5,5))
 > a
    V1 V2
1  -5 -5
2  -4 -4
3  -3 -3
4  -2 -2
5  -1 -1
6   0  0
7   1  1
8   2  2
9   3  3
10  4  4
11  5  5
 > b <- a$V1 > 0
 > b
  [1] FALSE FALSE FALSE FALSE FALSE FALSE  TRUE  TRUE  TRUE  TRUE  TRUE
 > a[b,]
    V1 V2
7   1  1
8   2  2
9   3  3
10  4  4
11  5  5
 > a[!b,]
   V1 V2
1 -5 -5
2 -4 -4
3 -3 -3
4 -2 -2
5 -1 -1
6  0  0

Hope that helps!

Ben