[R] if statements on vectors

Dimitris Rizopoulos d.rizopoulos at erasmusmc.nl
Thu Feb 24 10:37:19 CET 2011


there are also vectorized logical operators; have a look at the help 
page ?'&', and try this:

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)

position <- as.numeric((trend1 == 1 & trend2 == 1) | (trend1 == -1 & 
trend2 == -1))
position


I hope it helps.

Best,
Dimitris


On 2/24/2011 9:41 AM, Kushan Thakkar wrote:
> 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.
>

-- 
Dimitris Rizopoulos
Assistant Professor
Department of Biostatistics
Erasmus University Medical Center

Address: PO Box 2040, 3000 CA Rotterdam, the Netherlands
Tel: +31/(0)10/7043478
Fax: +31/(0)10/7043014
Web: http://www.erasmusmc.nl/biostatistiek/



More information about the R-help mailing list