Duncan Murdoch wrote:
> Shruthi Jayaram wrote:
>> Hi,
>>
>> How do I check for two conditions in an if loop? I want to check if a
>> value
>> lies between 2 other values.
>>   
> "if" isn't normally a loop, but what you want is the vectorized
> version, the ifelse() function.
>> 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.   
>
> C <- ifelse( X < A & A < Y, 0, A)

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

______________________________________________
R-help@r-project.org mailing list
https://stat.ethz.ch/mailman/listinfo/r-help
PLEASE do read the posting guide http://www.R-project.org/posting-guide.html
and provide commented, minimal, self-contained, reproducible code.

Reply via email to