1

I have data frame with two column say "a" and "b" now I want to create another column "c" which will take value 1 if the following condition satisfied:

a>x and within this subset b>y. x and y are arbitrary constant. The condition is somewhat nested. so if a>x returns 25 observation then b>y will search within that 25 observation NOT within entire data frame.

Joy
  • 379
  • 6
  • 14
  • 1
    Please see http://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example for how to help us help you answer your question. Also, I don't see how this is nested at all. What's wrong with `a>x & b>y` ? – Ari B. Friedman Apr 24 '12 at 20:00

1 Answers1

2

I really suspect you could have figured this out had you tried something...

R> x <- data.frame(a=1:10,b=10:1)
R> (x$c <- x$a > 3 & x$b > 4)
    a  b     c
1   1 10 FALSE
2   2  9 FALSE
3   3  8 FALSE
4   4  7  TRUE
5   5  6  TRUE
6   6  5  TRUE
7   7  4 FALSE
8   8  3 FALSE
9   9  2 FALSE
10 10  1 FALSE
Joshua Ulrich
  • 163,034
  • 29
  • 321
  • 400
  • When you do this are you avoiding R to evaluate `b>y` for the rows where `a>x` is `FALSE`? – João Daniel Apr 24 '12 at 20:15
  • @Joshua: Thanks this is what I am looking for. – Joy Apr 24 '12 at 20:21
  • @JoãoDaniel: `x$b > 4` is _evaluated_ for every element in the vector. Run the commands individually to see what they each return (`(xa 3); (xb 4); (xc – Joshua Ulrich Apr 24 '12 at 20:23
  • So actually it doesn't do what the questions asks for. The question says "so if a>x returns 25 observation then b>y will search within that 25 observation NOT within entire data frame.", and it doesn't do that, right? – João Daniel Apr 24 '12 at 20:30
  • @JoãoDaniel: you're getting stuck on semantics. Look at my answer. `x$c` is only `TRUE` IFF _both_ conditions are `TRUE`. It doesn't matter that I evaluated unnecessary elements for `x$b > 4`. – Joshua Ulrich Apr 24 '12 at 20:38
  • It's true when they say that sometimes what we view is not what we see. I could only think that the matter was to avoid evaluating all the elements of `b`. – João Daniel Apr 24 '12 at 20:44
  • @JoãoDaniel: that's very true. Now go use your new knowledge to write more efficient code! ;-) – Joshua Ulrich Apr 24 '12 at 20:47