Hands-On Programming with R by Garrett Grolemund

Hands-On Programming with R by Garrett Grolemund

Author:Garrett Grolemund
Language: eng
Format: epub, pdf
ISBN: 9781449359010
Publisher: O'Reilly Media
Published: 2014-03-15T00:00:00+00:00


if (num < 0) { num <- num * -1 }

If num < 0 is TRUE, R will multiply num by negative one, which will make num positive:

num <- -2 if (num < 0) { num <- num * -1 } num ## 2

If num < 0 is FALSE, R will do nothing and num will remain as it is—positive (or zero):

num <- 4 if (num < 0) { num <- num * -1 } num ## 4

The condition of an if statement must evaluate to a single TRUE or FALSE. If the condition creates a vector of TRUEs and FALSEs (which is easier to make than you may think), your if statement will print a warning message and use only the first element of the vector. Remember that you can condense vectors of logical values to a single TRUE or FALSE with the functions any and all.

You don’t have to limit your if statements to a single line of code; you can include as many lines as you like between the braces. For example, the following code uses many lines to ensure that num is positive. The additional lines print some informative statements if num begins as a negative number. R will skip the entire code block—print statements and all—if num begins as a positive number:



Download



Copyright Disclaimer:
This site does not store any files on its server. We only index and link to content provided by other sites. Please contact the content providers to delete copyright contents if any and email us, we'll remove relevant links or contents immediately.