Академический Документы
Профессиональный Документы
Культура Документы
Risahighlevelprogramminglanguageusedprimarilyforstatisticalcomputingandgraphics.The
goaloftheRProgrammingStyleGuideistomakeourRcodeeasiertoread,share,andverify.The
rulesbelowweredesignedincollaborationwiththeentireRusercommunityatGoogle.
Summary:RStyleRules
1.FileNames:endin.R
2.Identifiers:variable.name(orvariableName),FunctionName,kConstantName
3.LineLength:maximum80characters
4.Indentation:twospaces,notabs
5.Spacing
6.CurlyBraces:firstonsameline,lastonownline
7.else:Surroundelsewithbraces
8.Assignment:use<,not=
9.Semicolons:don'tusethem
10.GeneralLayoutandOrdering
11.CommentingGuidelines:allcommentsbeginwith#followedbyaspaceinlinecomments
needtwospacesbeforethe#
12.FunctionDefinitionsandCalls
13.FunctionDocumentation
14.ExampleFunction
15.TODOStyle:TODO(username)
Summary:RLanguageRules
1.attach:avoidusingit
2.Functions:errorsshouldberaisedusingstop()
3.ObjectsandMethods:avoidS4objectsandmethodswhenpossiblenevermixS3andS4
NotationandNaming
FileNames
Filenamesshouldendin.Rand,ofcourse,bemeaningful.
GOOD:predict_ad_revenue.R
BAD:foo.R
Identifiers
Don'tuseunderscores(_)orhyphens()inidentifiers.Identifiersshouldbenamedaccordingto
thefollowingconventions.Thepreferredformforvariablenamesisalllowercaselettersandwords
separatedwithdots(variable.name),butvariableNameisalsoacceptedfunctionnameshave
initialcapitallettersandnodots(FunctionName)constantsarenamedlikefunctionsbutwithan
initialk.
variable.nameispreferred,variableNameisaccepted
GOOD:avg.clicks
OK:avgClicks
BAD:avg_Clicks
FunctionName
GOOD:CalculateAvgClicks
BAD:calculate_avg_clicks,calculateAvgClicks
Makefunctionnamesverbs.
Exception:Whencreatingaclassedobject,thefunctionname(constructor)andclassshould
match(e.g.,lm).
kConstantName
Syntax
LineLength
Themaximumlinelengthis80characters.
Indentation
Whenindentingyourcode,usetwospaces.Neverusetabsormixtabsandspaces.
Exception:Whenalinebreakoccursinsideparentheses,alignthewrappedlinewiththefirst
characterinsidetheparenthesis.
Spacing
Placespacesaroundallbinaryoperators(=,+,,<,etc.).
Exception:Spacesaround='sareoptionalwhenpassingparametersinafunctioncall.
Donotplaceaspacebeforeacomma,butalwaysplaceoneafteracomma.
GOOD:
tab.prior<table(df[df$days.from.opt<0,"campaign.id"])
total<sum(x[,1])
total<sum(x[1,])
BAD:
tab.prior<table(df[df$days.from.opt<0,"campaign.id"])#Needsspacesaround'<'
tab.prior<table(df[df$days.from.opt<0,"campaign.id"])#Needsaspaceafterthecomma
tab.prior<table(df[df$days.from.opt<0,"campaign.id"])#Needsaspacebefore<
tab.prior<table(df[df$days.from.opt<0,"campaign.id"])#Needsspacesaround<
total<sum(x[,1])#Needsaspaceafterthecomma
total<sum(x[,1])#Needsaspaceafterthecomma,notbefore
Placeaspacebeforeleftparenthesis,exceptinafunctioncall.
GOOD:
if(debug)
BAD:
if(debug)
Extraspacing(i.e.,morethanonespaceinarow)isokayifitimprovesalignmentofequalssignsor
arrows(<).
plot(x=x.coord,
y=data.mat[,MakeColName(metric,ptiles[1],"roiOpt")],
ylim=ylim,
xlab="dates",
ylab=metric,
main=(paste(metric,"for3samples",sep="")))
Donotplacespacesaroundcodeinparenthesesorsquarebrackets.
Exception:Alwaysplaceaspaceafteracomma.
GOOD:
if(debug)
x[1,]
BAD:
if(debug)#Nospacesarounddebug
x[1,]#Needsaspaceafterthecomma
CurlyBraces
Anopeningcurlybraceshouldnevergoonitsownlineaclosingcurlybraceshouldalwaysgoon
itsownline.Youmayomitcurlybraceswhenablockconsistsofasinglestatementhowever,you
mustconsistentlyeitheruseornotusecurlybracesforsinglestatementblocks.
if(is.null(ylim)){
ylim<c(0,0.06)
}
xor(butnotboth)
if(is.null(ylim))
ylim<c(0,0.06)
Alwaysbeginthebodyofablockonanewline.
BAD:
if(is.null(ylim))ylim<c(0,0.06)
if(is.null(ylim)){ylim<c(0,0.06)}
Surroundelsewithbraces
Anelsestatementshouldalwaysbesurroundedonthesamelinebycurlybraces.
if(condition){
oneormorelines
}else{
oneormorelines
}
BAD:
if(condition){
oneormorelines
}
else{
oneormorelines
}
BAD:
if(condition)
oneline
else
oneline
Assignment
Use<,not=,forassignment.
GOOD:
x<5
BAD:
x=5
Semicolons
Donotterminateyourlineswithsemicolonsorusesemicolonstoputmorethanonecommandon
thesameline.(Semicolonsarenotnecessary,andareomittedforconsistencywithotherGoogle
styleguides.)
Organization
GeneralLayoutandOrdering
Ifeveryoneusesthesamegeneralordering,we'llbeabletoreadandunderstandeachother's
scriptsfasterandmoreeasily.
1.Copyrightstatementcomment
2.Authorcomment
3.Filedescriptioncomment,includingpurposeofprogram,inputs,andoutputs
4.source()andlibrary()statements
5.Functiondefinitions
6.Executedstatements,ifapplicable(e.g.,print,plot)
Unittestsshouldgoinaseparatefilenamedoriginalfilename_test.R.
CommentingGuidelines
Commentyourcode.Entirecommentedlinesshouldbeginwith#andonespace.
Shortcommentscanbeplacedaftercodeprecededbytwospaces,#,andthenonespace.
#Createhistogramoffrequencyofcampaignsbypctbudgetspent.
hist(df$pct.spent,
breaks="scott",#methodforchoosingnumberofbuckets
main="Histogram:fractionbudgetspentbycampaignid",
xlab="Fractionofbudgetspent",
ylab="Frequency(countofcampaignids)")
FunctionDefinitionsandCalls
Functiondefinitionsshouldfirstlistargumentswithoutdefaultvalues,followedbythosewithdefault
values.
Inbothfunctiondefinitionsandfunctioncalls,multipleargumentsperlineareallowedlinebreaks
areonlyallowedbetweenassignments.
GOOD:
PredictCTR<function(query,property,num.days,
show.plot=TRUE)
BAD:
PredictCTR<function(query,property,num.days,show.plot=
TRUE)
Ideally,unittestsshouldserveassamplefunctioncalls(forsharedlibraryroutines).
FunctionDocumentation
Functionsshouldcontainacommentssectionimmediatelybelowthefunctiondefinitionline.These
commentsshouldconsistofaonesentencedescriptionofthefunctionalistofthefunction's
arguments,denotedbyArgs:,withadescriptionofeach(includingthedatatype)andadescription
ofthereturnvalue,denotedbyReturns:.Thecommentsshouldbedescriptiveenoughthatacaller
canusethefunctionwithoutreadinganyofthefunction'scode.
ExampleFunction
CalculateSampleCovariance<function(x,y,verbose=TRUE){
#Computesthesamplecovariancebetweentwovectors.
#
#Args:
#x:Oneoftwovectorswhosesamplecovarianceistobecalculated.
#y:Theothervector.xandymusthavethesamelength,greaterthanone,
#withnomissingvalues.
#verbose:IfTRUE,printssamplecovariance;ifnot,not.DefaultisTRUE.
#
#Returns:
#Thesamplecovariancebetweenxandy.
n<length(x)
#Errorhandling
if(n<=1||n!=length(y)){
stop("Argumentsxandyhavedifferentlengths:",
length(x),"and",length(y),".")
}
if(TRUE%in%is.na(x)||TRUE%in%is.na(y)){
stop("Argumentsxandymustnothavemissingvalues.")
}
covariance<var(x,y)
if(verbose)
cat("Covariance=",round(covariance,4),".\n",sep="")
return(covariance)
}
TODOStyle
UseaconsistentstyleforTODOsthroughoutyourcode.
TODO(username):Explicitdescriptionofactiontobetaken
Language
Attach
Thepossibilitiesforcreatingerrorswhenusingattacharenumerous.Avoidit.
Functions
Errorsshouldberaisedusingstop().
ObjectsandMethods
TheSlanguagehastwoobjectsystems,S3andS4,bothofwhichareavailableinR.S3methods
aremoreinteractiveandflexible,whereasS4methodsaremoreformalandrigorous.(Foran
illustrationofthetwosystems,seeThomasLumley's"Programmer'sNiche:ASimpleClass,inS3
andS4"inRNews4/1,2004,pgs.3336:https://cran.rproject.org/doc/Rnews/Rnews_2004
1.pdf.)
UseS3objectsandmethodsunlessthereisastrongreasontouseS4objectsormethods.A
primaryjustificationforanS4objectwouldbetouseobjectsdirectlyinC++code.Aprimary
justificationforanS4generic/methodwouldbetodispatchontwoarguments.
AvoidmixingS3andS4:S4methodsignoreS3inheritanceandviceversa.
Exceptions
Thecodingconventionsdescribedaboveshouldbefollowed,unlessthereisgoodreasontodo
otherwise.Exceptionsincludelegacycodeandmodifyingthirdpartycode.
PartingWords
UsecommonsenseandBECONSISTENT.
Ifyouareeditingcode,takeafewminutestolookatthecodearoundyouanddetermineitsstyle.If
othersusespacesaroundtheirifclauses,youshould,too.Iftheircommentshavelittleboxesof
starsaroundthem,makeyourcommentshavelittleboxesofstarsaroundthem,too.
Thepointofhavingstyleguidelinesistohaveacommonvocabularyofcodingsopeoplecan
concentrateonwhatyouaresaying,ratherthanonhowyouaresayingit.Wepresentglobalstyle
rulesheresopeopleknowthevocabulary.Butlocalstyleisalsoimportant.Ifcodeyouaddtoafile
looksdrasticallydifferentfromtheexistingcodearoundit,thediscontinuitywillthrowreadersoutof
theirrhythmwhentheygotoreadit.Trytoavoidthis.
OK,enoughwritingaboutwritingcodethecodeitselfismuchmoreinteresting.Havefun!
References
http://www.maths.lth.se/help/R/RCC/RCodingConventions
http://ess.rproject.org/Foremacsusers.ThisrunsRinyouremacsandhasanemacsmode.