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.

1
  • 1
    Please see stackoverflow.com/questions/5963269/… 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 ? Commented Apr 24, 2012 at 20:00

1 Answer 1

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
Sign up to request clarification or add additional context in comments.

6 Comments

When you do this are you avoiding R to evaluate b>y for the rows where a>x is FALSE?
@JoãoDaniel: x$b > 4 is evaluated for every element in the vector. Run the commands individually to see what they each return ((xa <- x$a > 3); (xb <- x$b > 4); (xc <- xa & xb)). Elements in xc are only TRUE if the corresponding elements of xa and xb are both TRUE.
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ã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.
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.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.