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.

Appendix EProgramming in ROne of R’s advantages over many other statistical software packages is that at its core is aprogramming language with a consistent and relatively modern syntax. This allows us towrite functions that simplify our work and extend the functionality of R to our problemsat hand. The goal of this appendix is to introduce some of the key programming conceptsand give enough examples of simpler stuff. The curious reader can find much morein<strong>for</strong>mation in either An Introduction to R or R Language Definition, manualsaccompanying R, or in the books S Programming by Venables and Ripley andProgramming with Data: A Guide to the S Language by Chambers.E.1 Editing functionsProgramming can be repetitive: we write a function, test it, find errors, fix them, andrepeat until we are happy with the result. Knowing how to make this process as painlessas possible alleviates some of the tedium and lets us focus on what is important. Arecommended approach is to use text files and an external editor (such as Notepad inWindows) to edit files. The edit() function can also manipulate functions from thecommand line.E.1.1 <strong>Using</strong> edit()Let’s begin with the most studied of examples from computer programming: the “helloworld” function. We can define such a function on the command line with> hello = function() {cat("hello world\n")}> hello()[1] "hello world"This is a basic function that prints (using cat()) the response “hello world” no matter whatthe input is. The “\n” tells R to print a new line. If we wanted to make a change to thisfunction we could retype the definition with our desired changes. This is facilitated byusing the arrow keys. However, using the edit() function will let us use an editor to makethe changes, thereby providing more control over the editing process. We call edit() likethis:> hello = edit (hello) # assign results of edit()back to hello

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

Saved successfully!

Ooh no, something went wrong!