Skip to content

if statement

5 messages · Shruthi Jayaram, Duncan Murdoch, Carlos J. Gil Bellosta +2 more

#
Hi,

How do I check for two conditions in an if loop? I want to check if a value
lies between 2 other values.

For example, 

A <- ts(rnorm(120), freq=12, start=c(1992,8))
X <- 0.5
Y <- 0.8

I would like to create a new vector C for which C[i] is 0 if A[i] lies in
between X and Y. 

Would be grateful for any help. Sorry for asking such an R-newbie question! 

Shruthi
#
Shruthi Jayaram wrote:
"if" isn't normally a loop, but what you want is the vectorized version, 
the ifelse() function.
C <- ifelse( X < A & A < Y, 0, A)

Duncan Murdoch
#
Hello,

If you do

C <- A
C[A > X & A < Y] <- 0

you get what it seems you want.

Best regards,

Carlos J. Gil Bellosta
http://www.datanalytics.com
On Mon, 2009-01-05 at 03:41 -0800, Shruthi Jayaram wrote:
#
Hi


r-help-bounces at r-project.org napsal dne 05.01.2009 12:41:49:
value
in
Well, you do not say what you want for C values if A[i] is not in such 
interval. So

 C<-(A<X|A>Y)*1

gives you zeros in required positions and ones in other positions.

Regards
Petr
question!
http://www.R-project.org/posting-guide.html
#
Duncan Murdoch wrote:
or using Petr's hint:

C <- (A<X|A>Y)*A

which seems much faster on substantial inputs.

pay attention to whether your 'in between' is inclusive or not; the two
versions above are not equivalent.

vQ