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 371arg1, arg2, arg3When a function is defined, default values may be specified using the name=valuesyntax, as inarg1=default1, arg2=default2, arg3=default3Arguments need not have defaults, but defaults are generally a good idea. The defaultscan depend on other argument values, as R per<strong>for</strong>ms lazy evaluation. This will beillustrated in the upcoming example. A catch-all argument, …, can be used to passunspecified, named arguments along to function calls made inside the body of thefunction. Once a function is defined, the args () function will return the argument list.Since there can be many arguments to a function, there needs to be a convention <strong>for</strong>how arguments are handled when a function is called. R functions can be called witheither named arguments or positional arguments. The named arguments are matched first.They appear in the function call as name=value. The name should match one of thefunction’s arguments, or they will be passed along if a…argument is used. Namedarguments may be truncated, as long as the truncated <strong>for</strong>m uniquely identifies theargument. This will not work, though, if the argument appears in the function definitionafter a…argument. The use of named arguments is encouraged.When a function is defined, the arguments have a natural position. If a function iscalled without named arguments, R will try to match the arguments in the function call bytheir position. This can make <strong>for</strong> less typing, but it is harder to debug.Finally, if a function call does not include one of the function’s arguments but adefault is given, this default value will be used. If no default is specified, an error willoccur.We illustrate how R handles function arguments by an example.■ Example E.1: Our histogram function (how R handles function arguments) Thedefault hist () function in R is a bit lacking. First, as a histogram reminds us of theunderlying density, it should look like a density. That is, it should be normalized so thearea is 1. For similar reasons, it is nice to estimate the density and add it to the graphic.Finally, following the truehist () function of the MASS library, we use the “Scott” rule toselect the bins.Here is a first attempt at what we want:ourhist = function(x) {hist(x,breaks="Scott",probability=TRUE)lines(density(x))}We can type this in on the command line, or define a function stub and then use edit (), asin> ourhist = function(x) {}> ourhist = edit(ourhist) # now editTry it out.> x = rnorm(100)

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

Saved successfully!

Ooh no, something went wrong!