You are on page 1of 2

CSSS 508 Spring 2005

How to Write Functions in R


1. Open a text editor (for example, TextPad, Crimson Editor, XEmas!
2. "rite an # f$ntion
%or example,
square <- function(number)
{
answer <- number * number
return(answer)
}
square is t&e name of t&e f$ntion.
function is t&e # f$ntion t&at reates f$ntions.
number is t&e parameter (name of t&e 'al$e! passed to t&e s($are f$ntion.
{ delimits t&e )eginning of t&e f$ntion
} delimits t&e end of t&e f$ntion
return is t&e # f$ntion t&at speifies *&at t&e f$ntion ret$rns,
in t&is example, t&e 'al$e of answer
+. Sa'e t&e file (), on'ention *it& an .# extension!. -n t&is example, t&e file name is
.example.#/.
%or t&is exerise, *e0re going to p$t in some errors in o$r f$ntion. Color oding is as
follo*s1 red for *&at t&e $ser t,pes2 )l$e for response ), #1
square <- function(number)
{
answer <- number * nmber
return(number
}
+. Start #
3. 4se t&e f$ntion source to load ,o$r f$ntion into ,o$r # *or5spae1
> source(example.R)
6ote t&at t&e file name is in ($otes and s&o$ld inl$de eit&er t&e a)sol$te pat&, or t&e pat&
relati'e to t&e loation of ,o$r # *or5spae.
5. # *ill indiate an, .s,ntax/ errors at t&is point and t&e line n$m)er *&ere t&e, are loated.
%or example,
rror in parse(file! n! text! prompt) " s#ntax error on line $
1 &ttp177sde.*as&ington.ed$7training7o$rses7sss508
CSSS 508 Spring 2005
8. 9o )a5 to ,o$r text editor and fix t&e error(s!, resa'e t&e file, and reread (so$re! t&e
f$ntion in #.
:. "&en ,o$ get a prompt after .so$ring/ ,o$r file, t&en ,o$ an tr, $sing t&e f$ntion1
> square($)
8. ;t t&is point, ,o$ ma, get a .r$ntime/ error. %or example,
rror in square($) " %b&ect 'nmber' not foun(
<. One again, go )a5 to ,o$r text editor and fix t&e error(s!, resa'e t&e file, and reread (so$re!
t&e f$ntion in #.
10. T&e last 5ind of error ,o$ an get, is *&ere t&e f$ntion r$ns, )$t gi'es t&e *rong ans*er.
%or example,
> square($)
)*+ $
T&ese are often t&e &ardest errors to find )ea$se # an0t &elp ,o$. =o$ &a'en0t done
somet&ing t&at # doesn0t $nderstand, rat&er ,o$0'e made an error telling # *&at to do. # is
doing exatl, *&at ,o$ as5ed, )$t it0s not *&at ,o$ meant. Oftentimes to find t&is error, ,o$
need to go t&ro$g& t&e f$ntion line ), line, 'erif,ing t&e res$lt of ea& line $ntil ,o$ find
,o$r error. =o$ an do t&is eit&er ), feeding ea& line to t&e # *or5spae. Or ), *riting
t&e res$lt of ea& line eit&er to t&e *or5spae or to a file $sing t&e at(! f$ntion.
11. %inall,, after orreting all t&ese errors, ,o$r f$ntion r$ns properl,1
> square($)
)*+ ,$
2 &ttp177sde.*as&ington.ed$7training7o$rses7sss508

You might also like