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

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

Appendix E 377In this example varname is the variable i, and the vector is the set of numbers 10 through1. We didn’t use braces, as only one statement is called.To illustrate further, let’s consider a primitive way to compute a factorial. Thedefinition of the factorial of a positive integer is n!=n·(n−1)·····2·1.fact=function(x) {ret=1<strong>for</strong>(i in 1:x) {ret=ret*i}return(ret)}The loop runs over the values of the vector 1: x. At each stage the running result ismultiplied by the new value. We can verify that fact (5) returns 120. (This function isalready implemented in the f actor ial() function. Even so, it would be better written usingthe prod() function to avoid the loop.)The statements next and break (no parentheses) can be used to skip to the next value inthe loop (next) or to break out of the loop (break).<strong>Using</strong> while()The <strong>for</strong> () loop above is great to use when we know ahead of time what values we want toloop over. Sometimes we don’t. We want to repeat something as long as a condition ismet. For example, as long as a number is positive, or a number is larger than sometolerance. The function while () does just this. Its template iswhile (condition) {statement(s)}Here is a simple example that counts how many tails there are be<strong>for</strong>e the first heads.tosscoin = function() {coin = "tails"# initialize conditioncount = −1# get counting right this waywhile(coin == "tails") {coin = sample(c("heads","tails"),1)count = count+1}cat("There were",count,"tails be<strong>for</strong>e the firstheads\n")}The usage of the functions while () and <strong>for</strong> () can often be interchanged. For example, wecan rewrite the factorial example above with the while () function as follows:fact 1 = function(x) {ret = 1

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

Saved successfully!

Ooh no, something went wrong!