10.07.2015 Views

Using R for Introductory Statistics : John Verzani

Using R for Introductory Statistics : John Verzani

Using R for Introductory Statistics : John Verzani

SHOW MORE
SHOW LESS

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

Appendix E 376The logic should be clear. If the value of x is less than 0, the return value is −x. Otherwiseit is just x. This example will not work <strong>for</strong> a vector of numbers with more than oneelement as the built-in abs () function will.Suppose we wanted to improve our eda() function defined previously by making itaware of different types of x. For example, if x is a factor, we want to present oursummary differently. One simple way to do this is to have a conditional statement in thefunction, such asif(is.factor(x)) {## do factor summary} else if(is.numeric(x)) {## do numeric summary} else {## do a default summary}We could write such conditions <strong>for</strong> all the different types of data objects we have inmind. Sometimes the switch() function can help simplify the coding.There are problems with this example. If we want to add a new type of variable, thenthe original eda() function needs to be available. This is fine <strong>for</strong> functions we write, butwhat about functions written by others <strong>for</strong> the system? We wouldn’t want to modifythose. Fortunately, there are styles in R <strong>for</strong> writing functions that eliminate this concernthat are described in the section on object-oriented programming.E.2.4 LoopingComputers, unlike humans, are very happy to do things again and again and again.Repeating something is called looping. There are three functions <strong>for</strong> looping: <strong>for</strong>(),while(), and repeat (). The latter is least common and will be skipped here.<strong>for</strong>() loopsThe standard f or () loop has this basic structure:<strong>for</strong> (varname in seq) {statement(s)}The varname is the name of a variable, the seq can be any vector or list, and thestatements get executed <strong>for</strong> each value of seq. When seq is a vector, varname loops overeach value. The statements are evaluated with the given value <strong>for</strong> varname. When seq is alist, varname refers to each successive component in the list (the values seq [[i]], not seq[i]).A simple example is a countdown program:> <strong>for</strong>(i in 10:1) print(i) # say blastoff

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!