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 373freedman-diaconis, scottWe see that we can make changes to the defaults quite easily. The third line uses theSturges rule and green as the color.However, we also see that we can make an error. Look closely at the last line. Wewant to change the color to green but keep the default <strong>for</strong> the breaks rule. This didn’twork. That is because R was expecting a breaks rule as the second argument to thefunction. To override this positional matching of arguments we use named arguments.That is,> ourhist(x,col="green")will work. Why? First R matches by named arguments, such as col=“green”.Then it tries to match by partial matching of names. For example,> ourhist(x,c="green")will work, as no other arguments begin with the letter c. Finally R tries to match byposition.Default values can be written to depend on arguments given during the function call.The use of lazy evaluation of arguments allows this to happen. For example, it iscommon to have graphic labels depend on the name of the variable passed into afunction. To supply a default title <strong>for</strong> the histogram can be done as followsourhist = function(x,breaks="Scott",col="purple",main=deparse(substitute(x))) {hist(x,breaks=breaks,probability=TRUE,col=col,main=main)lines(density(x))}Now the default value <strong>for</strong> the main title is found by applying substitute () and deparse() tothe argument x. This has the effect of making a character string out of an R expression.The term “lazy” refers to the fact that the value <strong>for</strong> main= isn’t determined until it needsto be—when the function is called, not when the function is first defined.There are many other things we might want to modify about our histogram function,but mostly these are already there in the hist function. For example, changing the x-axislabel. It would be nice to be able to pass along arguments to our function ourhist () to theunderlying hist function. R does so with the …argument. When our function containsthree periods in a row,…, in the argument and in the body of the function, all extraarguments to our function are passed along. You may notice if you read the help page <strong>for</strong>hist () that it too has a…in its argument list.Again, modify the function, this time toourhist=function(x,breaks="Scott",col="purple",...) {hist(x,breaks=breaks,probability=TRUE,col=col,...)

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

Saved successfully!

Ooh no, something went wrong!