[R] if statements on vectors
Ivan Calandra
ivan.calandra at uni-hamburg.de
Thu Feb 24 10:40:27 CET 2011
Hi,
I think you want ifelse().
Assuming that length(trend2)=12 and not 14 as in the data you provided,
that should work:
position <- ifelse((trend1==1 & trend2==1)|(trend1==-1 &
trend2==-1),1,0) #btw, note the single "&" and single "|", not double
HTH,
Ivan
Le 2/24/2011 09:41, Kushan Thakkar a écrit :
> I have two vectors: both have possible values of 1,-1, or 0
>
> trend1<- c(1,1,1,1,1,1,-1,-1,-1,-1,-1,-1)
> trend2<- c(1,1,1,1,1,1,1,1,1,1,1,1,1,1,)
>
> i want to create a third vector that is conditional upon these two vectors:
>
> if (trend2 == 1&& trend1 == 1) {position<- 1}
> elseif (trend2 == -1&& trend1== -1) {position<- 1}
> else {position<- 0}
>
> based on this two conditions, the position vector should have a value:
>
> position: 1,1,1,1,1,1,0,0,0,0,0,0
>
> Is there a way to do this in R without explicitly going through a for loop?
> The if condition doesn't work as it only accept one condition (aka no
> vectors).
>
> [[alternative HTML version deleted]]
>
> ______________________________________________
> R-help at 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.
>
--
Ivan CALANDRA
PhD Student
University of Hamburg
Biozentrum Grindel und Zoologisches Museum
Abt. Säugetiere
Martin-Luther-King-Platz 3
D-20146 Hamburg, GERMANY
+49(0)40 42838 6231
ivan.calandra at uni-hamburg.de
**********
http://www.for771.uni-bonn.de
http://webapp5.rrz.uni-hamburg.de/mammals/eng/1525_8_1.php
More information about the R-help
mailing list