[R] New vector based on if/else statement within for loop?

Douglas M. Hultstrand dmhultst at metstat.com
Tue Oct 27 18:14:57 CET 2009


Hello,

I am trying to create a new vector (w) that is based on comparing two 
vectors (P and Z).  The compaison is simple (I  created a for loop that 
reassigns w based on if statement), all Z values >= 24 and P values <=1, 
w=88 else w=77.   I am not getting the correct results for w, see 
example code below.  Any thoughts or suggestions on the correct  method.

Thank you,
Doug

P <- c(0,1,2,3,4,5,0,1,5)
Z <- c(25,23,28,29,30,31,28,29,22)
w <- P

for (i in length(w)) {
    if(Z[i]>=24 && P[i]<=1) {
        w[i] = 88
        } else {
        w[i] = 77}
}

d.f <- data.frame(Z,P,w)
d.f
   Z P  w
1 25 0  0
2 23 1  1
3 28 2  2
4 29 3  3
5 30 4  4
6 31 5  5
7 28 0  0
8 29 1  1
9 22 5 77

-- 
---------------------------------
Douglas M. Hultstrand, MS
Senior Hydrometeorologist
Metstat, Inc. Windsor, Colorado
voice: 970.686.1253
email: dmhultst at metstat.com
web: http://www.metstat.com




More information about the R-help mailing list