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 375return(summary(x))summary}# returnLooking at the body of the eda () function we see that the par () settings are saved intoold.par. The on.exit () function executes commands when the function exits. In this case,it returns the original settings <strong>for</strong> par (). This usage is illustrated in the help page <strong>for</strong> par(). As this function changes the plot device by setting mf row=c (1, 3) to create threegraphs on one screen, it is nice to return to the old settings when we leave. The threegraphs are straight<strong>for</strong>ward. Finally, the last line uses return () to return the value of thesummary () function. In general, the last line evaluated is returned, but specifying thereturn value eliminates surprises.Try it out a few times. For example, look at the output of eda (rnorm (100)). Functionslike this are pretty handy. It would be nice to improve it a bit. In particular, the functionas written is good only <strong>for</strong> univariate, numeric data. What about eda <strong>for</strong> bivariate data?Categorical data? If we have categorical data, we might want to plot a barplot and returna summary.E.2.3 Conditional evaluationR has some standard ways to deal with conditional evaluation. Depending on a value ofsome condition, one of many things can be done.if ()The if () function allows us to do something based on a condition. It takes two <strong>for</strong>ms:an “if-then” <strong>for</strong>mif (condition) {statement(s) if condition is TRUE}and an “if-then-else” <strong>for</strong>mif (condition) {statement(s) if condition is TRUE} else {statements(s) if condition is FALSE}The condition is a logical expression, such as x > a or x == y. For example, the followingis a really bad way of defining an absolute-value function:abs=function(x) {if (x < a) {return(−x)} else {return(x)}}

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

Saved successfully!

Ooh no, something went wrong!