Douglas M. Hultstrand
2009-Oct-27 17:14 UTC
[R] New vector based on if/else statement within for loop?
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
Duncan Murdoch
2009-Oct-27 17:20 UTC
[R] New vector based on if/else statement within for loop?
On 10/27/2009 1:14 PM, Douglas M. Hultstrand wrote:> 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.Use ifelse(), not if ... else. It's ideal for tests like these.> > 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)) {That only sets i to one value, length(w). You could fix it by for (i in seq_along(w)) but ifelse() is better: w <- ifelse( Z >= 24 & P <= 1, 88, 77 ) Duncan Murdoch> 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 >