[R] Loops and vector operations

R. Michael Weylandt <michael.weylandt@gmail.com> michael.weylandt at gmail.com
Wed Dec 28 21:42:36 CET 2011


Look at ?ifelse. You'll need to nest them however. If you are feeling a little more ambitious this can be done with ?switch, but for clarity, I'd rather see pre-allocation followed by assignments  Something along this pattern:

out <- numeric(50)
x <- sample(3, 50, TRUE)
out[x==3] <- "A"
out[x==2] <- "B"
out[x==1] <- "C"

Not the fastest, but quite clear

HTH,

Michael

On Dec 28, 2011, at 10:55 AM, Mago84 <davidquiasmo at gmail.com> wrote:

> Dear all, 
> this is my first post and I´m very new at R, I don´t know if somebody can
> help with an issue.
> I´m doing some exercices and I don´t know if for example I can convert this
> for in an operation with vectors:
> 
> for (i in 2:n){
>    if (ES[i-1]==0 && sprd[i-1]>mediaSDP[i-1]  && sprd[i]<=mediaSDP[i]) {ES[i]
> <- -1} else
>    if((ES[i-1]==-1 || ES[i-1]==-15) && sprd[i]>media[i]) {ES[i] <- -15} else
>    if((ES[i-1]==-1 || ES[i-1]==-15) && sprd[i]<=media[i]) {ES[i] <- -17} else
>    if(ES[i-1]==0 && sprd[i-1]<mediaSDN[i-1] && sprd[i]>=mediaSDN[i])
> {ES[i] <- 1} else
>    if((ES[i-1]==1 || ES[i-1]==15)&& sprd[i]<media[i]) {ES[i] <- 15} else
>    if((ES[i-1]==1 || ES[i-1]==15)&& sprd[i]>=media[i]) {ES[i] <- 17}
> else {ES[i] <-0}
> }
> 
> Thanks a lot!!
> 
> --
> View this message in context: http://r.789695.n4.nabble.com/Loops-and-vector-operations-tp4240434p4240434.html
> Sent from the R help mailing list archive at Nabble.com.
> 
> ______________________________________________
> 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.



More information about the R-help mailing list