11.07.2015 Views

Preface to First Edition - lib

Preface to First Edition - lib

Preface to First Edition - lib

SHOW MORE
SHOW LESS
  • No tags were found...

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

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

16 AN INTRODUCTION TO R<strong>to</strong> light when writing our own functions for our own analysis tasks. AlthoughR is a full-featured programming language, writing small helper functions forour daily work is not <strong>to</strong>o complicated. We’ll study two example cases.At first, we want <strong>to</strong> add a robust measure of variability <strong>to</strong> the locationmeasures computed in the previous subsection. In addition <strong>to</strong> the medianprofit, computed viaR> median(Forbes2000$profits, na.rm = TRUE)[1] 0.2we want <strong>to</strong> compute the inter-quartile range, i.e., the difference betweenthe 3rd and 1st quartile. Although a quick search in the manual pages (viahelp("interquartile")) brings function IQR <strong>to</strong> our attention, we will approachthis task without making use of this <strong>to</strong>ol, but using function quantilefor computing sample quantiles only.A function in R is nothing but an object, and all objects are created equal.Thus, we ‘just’ have <strong>to</strong> assign a function object <strong>to</strong> a variable. A functionobject consists of an argument list, defining arguments and possibly defaultvalues, and a body defining the computations. The body starts and ends withbraces. Of course, the body is assumed <strong>to</strong> be valid R code. In most cases weexpect a function <strong>to</strong> return an object, therefore, the body will contain one ormore return statements the arguments of which define the return values.Returning <strong>to</strong> our example, we’ll name our function iqr. The iqr functionshould operate on numeric vec<strong>to</strong>rs, therefore it should have an argument x.This numeric vec<strong>to</strong>r will be passed on <strong>to</strong> the quantile function for computingthe sample quartiles. The required difference between the 3 rd and 1 st quartilecan then be computed using diff. The definition of our function reads asfollowsR> iqr IQR(xdata)[1] 1.495980However, when the numeric vec<strong>to</strong>r contains missing values, our function failsas the following example shows:R> xdata[1] iqr(xdata)© 2010 by Taylor and Francis Group, LLC

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

Saved successfully!

Ooh no, something went wrong!