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 370This command opens a text editor* to the function and allows us to edit. Make thesechanges, save, and exit.function(x) {cat("hello",x,"\n")}(No prompts are given, as we are doing this in the editor and not on the command line.)Now our function can take an argument, such as:> hello("kitty")hello kittyThe function fix() is an alternative interface to edit(), which does not require us to assignthe value back.E.2 <strong>Using</strong> functionsA function in R is defined by the following pieces:function (arguments) bodyThe body term is a block of commands. If there is more than one command in the body,they are put into a block using braces. A function declaration returns an object with classattribute “function.” A class attribute allows R to organize objects by type. The result of afunction declaration is usually assigned to a variable or function name, althoughsometimes, such as with sapply(), functions are used anonymously. In the example above,hello = function(x) {cat("hello",x,"\n")}the keyword function is used. The argument is simply the variable denoted x, and thebody is the single command cat ("hello",x,"\n"). In this simple case, where the body is asingle command, the function could be written without the braces, as inhello = function(x) cat("hello",x,"\n")* The default editor varies depending on the operating system used. The editor can be changed usingthe options () function, as in options(editor=“jedit”).E.2.1 Function argumentsWhen we use a function, we typically pass it arguments, so that we can get differentoutputs. The arguments to a function are specified as a list of variable names separated bycommas, such as

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

Saved successfully!

Ooh no, something went wrong!