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

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

Simulation 1676.4.3 The function bodyThe function body is a block of commands enclosed in braces. As mentioned, the bracesare optional if there is a single command. The return value <strong>for</strong> a function is the lastcommand executed. The function return() will <strong>for</strong>ce the return of a function, with itsargument becoming the return value.Some commands executed during a function behave differently from when they areexecuted at the command line—in particular, printing and assignment.During interactive usage, typing the name of an R object causes it to be “printed.” Thisshows the contents in a nice way, and varies by the type of object. For example, factorsand data vectors print differently. Inside a function, nothing is printed unless you ask it tobe. * The function print() will display an object as though it were typed on the commandline. The function cat() can be used to concatenate values together. Unlike print(), thecat() function will not print a new line character, nor the element numbers, such as [1]. Anew line can be printed by including "\n" in the cat() command. When a function iscalled, the return value will print unless it is assigned to some object. If you don’t wantthis, such as when producing a graphic, the function invisible() will suppress the printing.Assignment inside a function block is a little different. Within a block, assignment to avariable masks any variable outside the block. This example defines x to be 5 outside theblock, but then assigns x to be 6 inside the block. When x is printed inside the block thevalue of 6 shows; however, x has not changed once outside the block.> x = 5> f = function() {+ x = 6+ x+}> f()[1] 6> x[1] 5If you really want to <strong>for</strong>ce x to change inside the block, the global assignment operator f = function() print (x)> f()[1] 5> rm(x)> f ()Error: Object “x” not foundWhen no variable named x is be found, an error message is issued.

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

Saved successfully!

Ooh no, something went wrong!