Friday 15 June 2012

if statement - Using ifelse in R -


I if and ifelse . Sample data is tested and there are columns for X, Y, and Z testing.)

Statement to be coded

  if (X & Gt; 0) {if (y> gt;) {l = 2} and {l = 5} if (z> 0) {m = l + 2} and {m = 5}}   

R code using ifelse

  test $ l < -with (test, ifelse ((x> 0 & amp; y> 0), 2, ifelse ((x> 0 & amp; y; lt; = 0), 5, ???) )) Tested $ m < -with (test, ifelse ((> 0 & amp; z> 0), l + 2, ifelse (X & gt; 0 & amp; z> & lt; = 0), 5, ??? )))   

Where, ??? Specifies that there is no value according to the statement given above on x have no value in other words.

Next, I work to see if and ifel combination:

  if (test $ z> 0) { $ L  0,2,5)) test $ m  0, l + 2,5))}   

This code is fine, but there is a warning message (because z is a column vector)

  if (test $ z> gt; 0) {length of position & gt; 1 and only the first element will be used   

I have only been working with vector since apple but, in this regard, I have no There is no luck. Any ideas?

I will use the transform twice for example:

  Testing & lt; - data.frame (x = c (-1,1,2), y = c (1, -2,3), z = c (1, -5,5)) test (LIT) - transform (test, M = ifelse (x> 0, ifelse (z> 0), transform (test, l = ifelse (x> 0, ifelse (y> 0, 5, L + 2,5), NA) ) Xyzlm 1 -1 1 1 NA NA 2 1 -2 -5 5 5 3 2 3 5 2 4   

Note that I for the case of NA X <0. You You can use the example for example:

  test & lt; - data.frame (x = c (-1,1,2), y = c (1, - 2) , 3), Z = C (1, -5,5)) transform (test, L & l; - iFeil (x> 0, affile (y> 2.25), NA), M = Eiffel ( X> 0, ifell (z> 0, l + 2,5), ny)) xyz c.NA..5..2.m -1 -1 1 1a 2 2 2 -2.55 5 3 2 3 5 2 4   

But personally I like the first one for readability, apart from this, you probably need to change the column name.

No comments:

Post a Comment