Skip to content
Back to formatted view

Raw Message

Message-ID: <77E4AC7D-54A1-4BA7-9321-5F4D0AE328A8@gmail.com>
Date: 2011-12-28T20:42:36Z
From: michael.weylandt at gmail.com (R. Michael Weylandt
Subject: Loops and vector operations
In-Reply-To: <1325091357638-4240434.post@n4.nabble.com>

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] &amp;&amp; sprd[i]>=mediaSDN[i])
> {ES[i] <- 1} else
>    if((ES[i-1]==1 || ES[i-1]==15)&& sprd[i]<media[i]) {ES[i] &lt;- 15} else
>    if((ES[i-1]==1 || ES[i-1]==15)&amp;&amp; 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.