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.

<strong>Using</strong> R <strong>for</strong> introductory statistics 166The edit() function works similarly, but you must assign its return value, as in> f = edit(f)6.4.2 Function argumentsA function usually has a different answer depending on the value of its arguments.Passing arguments to R functions is quite flexible. We can do this by name or position.As well, as writers of functions, we can create reasonable defaults.Let’s look at our function f, which finds the mean of ten exponentials. If we edit itsdefinition to bef=function(n=10){mean(rexp(n))}then we can pass in the size of the sample, n, as a parameter. We can call this function inseveral ways: f(), f(10), and f(n=10) are all the same and use n=10. This command usesn=100: f(100). The first argument to f is named n and is given a default value of 10 by then=10 specification in the definition. Calling f by f() uses the defaults values. Calling f byf(100) uses the position of the argument to assign the values inside the function. In thiscase, the 100 is assigned to the only argument, n=. When we call f with f(n=100) we usea named argument. With this style there is no doubt what value n is being set to.With fdefined, simulating 200 samples of <strong>for</strong> n=50 can be done as follows:> res = c()> <strong>for</strong>d in 1:200) res[i]=f(n = 50)Better still, we might want to pass in a parameter to the exponential. The rate of theexponential is 1 over its mean. So changing f tof = function(n = 10, rate = 1) {mean(rexp(n, rate = rate))}sets the first argument of f to n with a default of 10 and the second to rate with a defaultof 1. This allows us to change the size and rate as in f(50,2), which would take 50 X i ’seach with rate 2 or mean 1/2. Alternately, we could do f(rate=1/2), which would use thedefault of 10 <strong>for</strong> n and use the value of 1/2 <strong>for</strong> rate. (Note that f (1/2) will not do this, asthe 1/2 would match the position <strong>for</strong> n and not that of rate.)The arguments of a function are returned by the args() command. This can help yousort out the available arguments and their names as a quick alternative to the morein<strong>for</strong>mative help page. When consulting the help pages of R’s builtin functions,the…argument appears frequently. This argument allows the function writer to pass alongarbitrarily named arguments to function calls inside the body of a function.

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

Saved successfully!

Ooh no, something went wrong!