Later the Perl script is executed with the command-line arguments that user specified. The options are parsed and saved into a json file.
Parsingcommand-lineargumentsbyGetopt::Long
ZuguangGu([email protected])
2020-12-15
TherearealreadyseveralRpackageswhichparsecommand-lineargumentssuchasgetopt,optparse,argparse,docopt.HereGetoptLongisanothercommand-lineargumentparser(actuallyitwasdevelopedveryearly,thefirstCRANversionwasin2013)whichwrapsthepowerfulPerlmoduleGetopt::Long.GetoptLongpackagealsoprovidessomeadaptationsforeasieruseinR.
UsingGetoptLongissimpleespeciallyforusershavingPerlexperience(Oops,ageexposed:))becausethespecificationisalmostthesameasinPerl.TheoriginalwebsiteofGetopt::Longisalwaysyourbestreference.
Note:tousethispackage,Perlshouldbeinstalled.
Workflowofthewrapping
TheGetoptLongRpackageautomaticallygeneratesaPerlscriptaccordingtothespecificationsintheRscript.LaterthePerlscriptisexecutedwiththecommand-lineargumentsthatuserspecified.Theoptionsareparsedandsavedintoajsonfile.FinallyRreadsbackthejsonfileandformatsthemasRvariables.
FollowingfigureshowshowtheRpackageworksforparsingthecommand-linearguments.
Aquickexample
Specifyasavector
ThefollowingexamplegivesyousomefeelsofusingGetoptLongpackage.ThefollowingcodeissavedintoanRscriptnamedfoo.R.
library(GetoptLong)
cutoff=0.05
GetoptLong(
"number=i","Numberofitems.",
"cutoff=f","Cutoffforfilteringresults.",
"verbose","Printmessage."
)
TheRscriptcanbeexecutedas:
~\>Rscriptfoo.R--number4--cutoff0.01--verbose
~\>Rscriptfoo.R--number=4--cutoff=0.01--verbose
~\>Rscriptfoo.R-n4-c0.01-v
~\>Rscriptfoo.R-n4--verbose
Inthisexample,numberisamandatoryoptionanditshouldonlybeinintegermode.cutoffisoptionalanditalreadyhasadefaultvalue0.05.verboseisalogicaloption.Ifparsingissuccessful,twovariablesnumberandverbosewillbeimportedintotheworkingenvironmentwiththespecifiedvalues.Valueforcutoffwillbeupdatedifitisspecifiedincommand-line.
Datatypesareautomaticallychecked.E.g.,ifcutoffisspecifiedwithacharacter,anerrorwillbethrown.
Theoptionusagetriggeredby--helpisautomaticallygenerated.Therearetwostyles:
Theone-columnstyle:
Usage:Rscriptfoo.R[options]
Options:
--number,-ninteger
Numberofitems.
--cutoff,-cnumeric
Cutoffforfilteringresults.
[default:0.05]
--verbose
Printmessage.
--help,-h
Printhelpmessageandexit.
--version
Printversioninformationandexit.
Orthetwo-columnstyle:
Usage:Rscriptfoo.R[options]
Options:
--number,-nNumberofitems.
[type:int]
--cutoff,-cCutoffforfilteringresults.
[type:num][default:0.05]
--verbosePrintmessage.
--help,-hPrinthelpmessageandexit.
--versionPrintversioninformationandexit.
Youcanfindtheshortoptionnames(insingleletters)areautomaticallyadded.Theinformationofdefaultvaluesisaddedaswell.
Specifyasatemplate
Thespecificationcanalsobesetasatemplatewherethespecificationsaremarkedby<>.
spec="
Thisisanexampleofusingtemplatetospecifyoptions.
Usage:Rscriptfoo.R[options]
Options:
Numberofitems.
Cutoffforfilteringresults.
Printmessages.
Contact:name@address
"
GetoptLong(spec,template_control=list(opt_width=21))
Theparameteropt_widthcontrolsthemaximalwidthoftheoptiondescription(i.e.,--number,-ninteger,--cutoff,-cnumericand--verbose).
CallingRscriptfoo.R--helpgeneratesthefollowingmessage:
Thisisanexampleofusingtemplatetospecifyoptions.
Usage:Rscriptfoo.R[options]
Options:
--number,-nintegerNumberofitems.
--cutoff,-cnumericCutoffforfilteringresults.
--verbosePrintmessages.
Contact:name@address
Advantages
Thereareseveraladvantagescomparedtoothercommand-lineargumentparserpackages.ThemajoradvantagecomesfromtheGetopt::LongPerlmodulewhichactuallyparsestheoptions.TheGetopt::Longmoduleprovidesaflexible,smartandcompactwayforspecifyingcommand-linearguments.Themajorfeaturesare:
Variousformatsofspecifyingoptionswithvalues,suchas
-s24-s24
or
--size24--size=24-size24-size=24
Single-letteroptionscanbebundled:
-a-b-c-abs
Optionswithmultiplenames.Withthefollowingspecification,--length,--heightarethesame.
length|height=f
Automaticallysupportsingle-letteroptions.Ifthefirstletterofanoptionisuniquetoallotheroptions,thefirstlettercanbeusedasanoptionaloptionname.Forexample,iflandhareunique,--length,--height,-land-hsetthesameoption.
length|height=f--length--height-l-h
Richoptiondatatypes,includingscalar,vector(arrayinPerl),list(hashinPerl).Forexample:
length=iasingleintegerscalar
name=sasinglecharacterscalar
canbespecifiedas:
--length1--namea
or
length=i@aintegervector
name=s@acharactervector
length=i{2,}aintegervector,atleasttwoelements
name=s{2,}acharactervector,atleasttwoelements
canbespecifiedas:
--length123--nameabc
or
length=i%name-valuepair,valuesshouldbeintegers
name=s%name-valuepair,valuesshouldbecharacters
tobespecifiedas:
--lengthfoo=1bar=3--namefoo=abar=b
ThefeaturesfromRpartare:
Itautomaticllygeneratesoptionusageintwostyles.Thedatatypeanddefaultvalueofoptionsareautomaticallydetectedandincluded.
Itsupportsspecifyingtheusageinatemplatewhichallowsmorecomplextextofoptionusage.
Itallowsgroupingoptions.
Itprovidesanaturalandconvenientwaytospecifydefaults.
Customizethespecifications
Eachspecifierinoptionsconsistsoftwoparts:thenamespecificationandtheargumentspecification:
length|size|l=i@
Herelength|size|lisalistofalternativenamesseparatedby|.Theremainingpartisargumentspecificationwhichdefinesthemodeandamountofarguments.
Specifyanyofalternativeoptionnamefromcommand-lineisokanditdoesn’tmatterwhetherusingoneortwoslashinfrontoftheoptionname.Sometimesyouevendon’tneedtospecifycompleteoptionnames,youonlyneedtomakesurethepartialnamematchisunique.Ifthepartialmatchisnotuniqe,itwillthrowanerror.Foraboveexample,wecanspecifytheargumentlike:
~\>Rscriptfoo.R--length1
~\>Rscriptfoo.R--length=1#adding"="isalsook
~\>Rscriptfoo.R-len1
~\>Rscriptfoo.R-lengt1#thisisalsook,butnotsuggested
~\>Rscriptfoo.R--size1
~\>Rscriptfoo.R-l1
Optionsforargumentspecificationare:
noargumentspecification:takingnoargument.Optionsarelogical.
!:takingnoargument.Optionsarelogical.Youcansetitsopositevaluebyaddingitwithnoorno-.E.g.,foo!allows--fooaswellas--nofooand--no-foo.
=type[desttype][repeat]:optionsshouldhavearguments(oroptionsshouldhavevaluesspecified).E.g.tag=i@whereicorrespondstotype,and@correspondstodesttype,ortag=i{2,}where{2,}correspondstorepeat.
Pleasenote:[type][desttype]isnotsupportedhere.Weuseanotherwaytodefinemandatoryoptionsandoptionaloptions.Ifyoudon’tknowwhatitis,justignorethisparagraph.
Availabletypeoptionsare:
s:strings
i:integers
F:realnumbers
o:extendedinteger,anoctalstring(0followedby0,1..7),orahexadecimalstring(0xfollowedby0..9,A..F,caseinsensitive),orabinarystring(0bfollowedbyaseriesof0and1).
Availabledesttypesettingsare:
@:array,allowmorethanoneargumentsforanoption.
%:hash,allowargumentslikename=value.
nothing:scalar,singleargumentforsingleoption.
Availablerepeatsettingsareformattedas{\d,\d}.Notethereisnospacecharacterinside:
{2}:exactly2argumentsforanoption.
{2,}:atleast2argumentsforanoption.
{,4}:atmost4argumentsforanoption.
{2,5}:minimal2andmaximal5argumentsforanoption.
Notedesttypeandrepeatcannotbeusedatthesametime.
InthePerlmodule,tag=i@onlyallows,e.g.,specificationof--tag1--tag2while--tag12isnotallowedwhichisonlypossiblebytag=i{1,}.IntheRpackage,[email protected],tag=i%onlyallows--tagname1=value1--tagname2=value2inthePerlmodule.IntheRpackage,italsoallows--tagname1=value1name2=value2.
Followingtablecontainsexamplesforeachtypeofoptionspecification:
Options
Command-linearguments
Valueoftag
tag=i
–tag1
1
–tag=1
1
-t1
1
–tag1–tag2
2.Hereonlytakethelastone
–tag0.1
Error:Value“0.1”invalidforoptiontag(numberexpected)
–taga
Error:Value“a”invalidforoptiontag(numberexpected)
–tag
Error:Optiontagrequiresanargument
noargument
tagismandatory,pleasespecifyit
tag=s
–tag1
“1”.Heredoublequoteisusedbecauseitisspecifiedasastring.
–tag0.1
“0.1”
–taga
“a”
tag=f
–tag1
1
–tag0.1
0.1
–taga
Error:Value“a”invalidforoptiontag(realnumberexpected)
tag=o
–tag1
1
–tag0b001001
9
–tag0721
465
–tag0xaf2
2802
-tag0.1
Error:Value“0.1”invalidforoptiontag(extendednumberexpected)
–taga
Error:Value“a”invalidforoptiontag(extendednumberexpected)
tag
–tag1
TRUE
–tag0
TRUE,itdoesn’tcarethevaluefortheoption.
–tag0.1
TRUE
–taga
TRUE
–tag
TRUE
noargument
FALSE
tag!
–tag
TRUE
–no-tag
FALSE
tag=i@
–tag1
1
–tag12
c(1,2)
–tag1–tag2
c(1,2)
–tag=1–tag=2
c(1,2)
tag=i%
–tag1
Error:Optiontag,key“1”,requiresavalue
–tagfoo=1–tagbar=2
list(foo=1,bar=2),tagisalist.
–tagfoo=1bar=2
list(foo=1,bar=2),tagisalist.
tag=i{2}
–tag1
Error:Insufficientargumentsforoptiontag
–tag12
c(1,2)
–tag1–tag2
Error:Value“–tag”invalidforoptiontag
tag=i{2,}
–tag1
Error:Insufficientargumentsforoptiontag
–tag12
c(1,2)
–tag123
c(1,2,3)
tag=i{,2}
–tag1
1
–tag12
c(1,2)
–tag123
c(1,2)
Wheredotheoptionvaluesgo
Optionswillbeimportedintouser’senvironmentasRvariablesbydefault.Thefirstoptionnameinallalternativenameswillbetakenasthenameofthevariable,(e.g.forspecificationoflength|size=s,lengthwillbeusedasthevariablename.),whichmeans,itmustbeavalidRvariablename.AnydefinitionofthesevariablesinfrontofGetoptLong()willbetreatedasdefaultvaluesforthecorrespondingoptions.Ifoptionsalreadyhavedefaultvalues,theyareoptionalincommand-line.IfthevariableisdefinedasafunctionbeforeGetoptLong()iscalled,itistreatedasundefined.Pleasenoteyouroptionnamesshouldnotstartwiththedot.AlthoughitisvalidforRvariablesbutitisnotallowedforGetopt::Longmodule.
Forthefollowingexample:
library(GetoptLong)
cutoff=0.05
GetoptLong(
"number=i{1,}","Numberofitems.",
"cutoff=f","Cutoffforfilteringresults.",
"param=s%","Parametersspecifiedbyname=valuepairs.",
"verbose","Printmessage."
)
print(number)
print(cutoff)
print(param)
print(verbose)
acallingfromcommand-line:
Rscriptfoo.R--number12--paramvar1=avar2=b--verbose
willprint
[1]12
[1]0.05
$var1
[1]"a"
$var2
[1]"b"
[1]TRUE
Therearetwowaystospecifylogicaloptions,e.g.,verboseandverbose!.verbosealwaystakesFALSEasdefaultandyoucannotsetdefaultvalueforit,whileyoucansetdefaultforverbose!.E.g.:
verbose=TRUE
GetoptLong(
"verbose!","Printmessage."
)
If--verbose/--no-verboseisnotspecified,thevariableverboseisTRUE.If--verboseisspecified,verboseisTRUEandif--no-verboseisspecified,verboseisFALSE.
Ifyoudon’twanttodirectlyexportoptionsasvariables,youcanassignenvirargumentwithanenvironmentvariablesothatalltheoptionvaluesgothere.
opt=new.env()
opt$cutoff=0.05
GetoptLong(
"number=i@","Numberofitems.",
"cutoff=f","Cutoffforfilteringresults.",
"param=s%","Parametersspecifiedbyname=valuepairs.",
"verbose","Printmessage.",
envir=opt
)
print(as.list(opt))
acallingfromcommand-line:
Rscriptfoo.R--number12--paramvar1=avar2=b--verbose
willprint
$cutoff
[1]0.05
$number
[1]12
$param
$param$var1
[1]"a"
$param$var2
[1]"b"
$verbose
[1]TRUE
Helpoption
helpisareservedoption,whichmeans,youcannotuseitasyours.
Optionusageisautomaticallygeneratedandcanberetrievedbysetting--helpinthecommand.Infollowingexample,Icreateanoptionspecificationthatcontainsalltypesofoptions(withlongdescriptions):
GetoptLong(
"count=i",paste("Thisisacount.Thisisacount.Thisisacount.",
"Thisisacount.Thisisacount.Thisisacount."),
"number=f",paste("Thisisanumber.Thisisanumber.Thisisanumber.",
"Thisisanumber.Thisisanumber.Thisisanumber."),
"array=f@",paste("Thisisanarray.Thisisanarray.Thisisanarray.",
"Thisisanarray.Thisisanarray.Thisisanarray."),
"hash=s%",paste("Thisisahash.Thisisahash.Thisisahash.",
"Thisisahash.Thisisahash.Thisisahash."),
"verbose!","Whethershowmessages",
"flag","anon-senseoption"
)
Theoptionusageisasfollows.Here,forexample,thesingle-letteroption-cfor--countisautomaticallyextractedwhilenotfor--helpbecausehmatchestwooptions.
Usage:Rscriptfoo.R[options]
Options:
--count,-cinteger
Thisisacount.Thisisacount.Thisisacount.Thisisacount.Thisis
acount.Thisisacount.
--number,-nnumeric
Thisisanumber.Thisisanumber.Thisisanumber.Thisisanumber.This
isanumber.Thisisanumber.
--array,-a[numeric,...]
Thisisanarray.Thisisanarray.Thisisanarray.Thisisanarray.This
isanarray.Thisisanarray.
--hash{name=character,...}
Thisisahash.Thisisahash.Thisisahash.Thisisahash.Thisisa
hash.Thisisahash.
--verbose,-no-verbose
Whethershowmessages
[default:off]
--flag,-f
anon-senseoption
--help
Printhelpmessageandexit.
--version
Printversioninformationandexit.
Ifdefaultvaluesforoptionsareprovided,theyareproperlyinsertedtotheusagemessage.
count=1
number=0.1
array=c(1,2)
hash=list("foo"="a","bar"="b")
verbose=TRUE
GetoptLong(
...
)
Usage:Rscriptfoo.R[options]
Options:
--count,-cinteger
Thisisacount.Thisisacount.Thisisacount.Thisisacount.Thisis
acount.Thisisacount.
[default:1]
--number,-nnumeric
Thisisanumber.Thisisanumber.Thisisanumber.Thisisanumber.This
isanumber.Thisisanumber.
[default:0.1]
--array,-a[numeric,...]
Thisisanarray.Thisisanarray.Thisisanarray.Thisisanarray.This
isanarray.Thisisanarray.
[default:1,2]
--hash{name=character,...}
Thisisahash.Thisisahash.Thisisahash.Thisisahash.Thisisa
hash.Thisisahash.
[default:foo=a,bar=b]
--verbose,-no-verbose
Whethershowmessages
[default:on]
--flag,-f
anon-senseoption
--help
Printhelpmessageandexit.
--version
Printversioninformationandexit.
Theglobalparametershelp_stylecanbesettotwo-columntochangetoanotherstyle:
GetoptLong.options(help_style="two-column")
#specifyingthedefaults
GetoptLong{
...
}
Usage:Rscriptfoo.R[options]
Options:
--count,-cThisisacount.Thisisacount.Thisisacount.
[type:int]Thisisacount.Thisisacount.Thisisacount.
[default:1]
--number,-nThisisanumber.Thisisanumber.Thisisa
[type:num]number.Thisisanumber.Thisisanumber.Thisis
anumber.
[default:0.1]
--array,-aThisisanarray.Thisisanarray.Thisisan
[type:[num,...]]array.Thisisanarray.Thisisanarray.Thisis
anarray.
[default:1,2]
--hashThisisahash.Thisisahash.Thisisahash.This
[type:{name=chr,...}]isahash.Thisisahash.Thisisahash.
[default:foo=a,bar=b]
--verbose,-no-verboseWhethershowmessages
[default:on]
--flag,-fanon-senseoption
--helpPrinthelpmessageandexit.
--versionPrintversioninformationandexit.
Whenoptionsarespecifiedasname-valuepairs,thesesuboptionscanbedocumentedasfollows.Notethespecificationsofe.g.foo$name1areonlyfortheusagemessage.
foo=list(a=1,b=2)
GetoptLong(
"foo=i%",paste("Thisisfoo.Thisisfoo.Thisisfoo.Thisisfoo.",
"Thisisfoo.Thisisfoo.Thisisfoo.Thisisfoo."),
"foo$name1",paste("name1infoo.name1infoo.name1infoo.name1infoo.",
"name1infoo.name1infoo.name1infoo.name1infoo."),
"foo$name2",paste("name2infoo.name2infoo.name2infoo.name2infoo.",
"name2infoo.name2infoo.name2infoo.name2infoo."),
"bar=s%",paste("Thisisbar.Thisisbar.Thisisbar.Thisisbar.",
"Thisisbar.Thisisbar.Thisisbar.Thisisbar."),
"bar$name3",paste("name3inbar.name3inbar.name3inbar.name3inbar.",
"name3inbar.name3inbar.name3inbar.name3inbar."),
"bar$name4",paste("name4inbar.name4inbar.name4inbar.name4inbar.",
"name4inbar.name4inbar.name4inbar.name4inbar.")
)
Usage:Rscriptfoo.R[options]
Options:
--foo,-f{name=integer,...}
Thisisfoo.Thisisfoo.Thisisfoo.Thisisfoo.Thisisfoo.Thisis
foo.Thisisfoo.Thisisfoo.
[default:a=1,b=2]
Subnamedoptions:
name1=integername1infoo.name1infoo.name1infoo.name1infoo.name1
infoo.name1infoo.name1infoo.name1infoo.
name2=integername2infoo.name2infoo.name2infoo.name2infoo.name2
infoo.name2infoo.name2infoo.name2infoo.
--bar,-b{name=character,...}
Thisisbar.Thisisbar.Thisisbar.Thisisbar.Thisisbar.Thisis
bar.Thisisbar.Thisisbar.
Subnamedoptions:
name3=charactername3inbar.name3inbar.name3inbar.name3inbar.name3
inbar.name3inbar.name3inbar.name3inbar.
name4=charactername4inbar.name4inbar.name4inbar.name4inbar.name4
inbar.name4inbar.name4inbar.name4inbar.
--help,-h
Printhelpmessageandexit.
--version,-v
Printversioninformationandexit.
Andthetwo-columnstyleforthesuboptions.
GetoptLong.options(help_style="two-column")
GetoptLong{
...
}
Usage:Rscriptfoo.R[options]
Options:
--foo,-fThisisfoo.Thisisfoo.Thisisfoo.Thisisfoo.
[type:{name=int,...}]Thisisfoo.Thisisfoo.Thisisfoo.Thisisfoo.
[default:a=1,b=2]
Subnamedoptions:
name1=intname1infoo.name1infoo.name1infoo.
name1infoo.name1infoo.name1infoo.
name1infoo.name1infoo.
name2=intname2infoo.name2infoo.name2infoo.
name2infoo.name2infoo.name2infoo.
name2infoo.name2infoo.
--bar,-bThisisbar.Thisisbar.Thisisbar.Thisisbar.
[type:{name=chr,...}]Thisisbar.Thisisbar.Thisisbar.Thisisbar.
Subnamedoptions:
name3=chrname3inbar.name3inbar.name3inbar.
name3inbar.name3inbar.name3inbar.
name3inbar.name3inbar.
name4=chrname4inbar.name4inbar.name4inbar.
name4inbar.name4inbar.name4inbar.
name4inbar.name4inbar.
--help,-hPrinthelpmessageandexit.
--version,-vPrintversioninformationandexit.
Extratextsuchheadandfootoftheusagemessagecanbesetwithhelp_headandhelp_footarguments:
GetoptLong(
help_head="Thisisademonstrationofaddingusageheadandfoot.",
"number=i","Numberofitems.",
"cutoff=f","Cutoffforfilteringresults.",
"verbose","Printmessage.",
help_foot="Pleasecontactname@address."
)
Thisisademonstrationofaddingusageheadandfoot.
Usage:Rscriptfoo.R[options]
Options:
--number,-ninteger
Numberofitems.
--cutoff,-cnumeric
Cutoffforfilteringresults.
--verbose
Printmessage.
--help,-h
Printhelpmessageandexit.
--version
Printversioninformationandexit.
Pleasecontactname@address.
Theoptionsintheusagetextcanbegroupedbysettingseparatorlines.Theseparatorlineshouldcontaintwoelements:theseparatorandthedescription.Theseparatorcanbeanycharacterin-+=#%withanylength.
count=1
array=c(0.1,0.2)
GetoptLong(
"--------","Binaryoptions:",
"verbose!","Whethershowmessages",
"flag","anon-senseoption",
"-------","Single-valueoptions:",
"count=i",paste("Thisisacount.Thisisacount.Thisisacount.",
"Thisisacount.Thisisacount.Thisisacount."),
"number=f",paste("Thisisanumber.Thisisanumber.Thisisanumber.",
"Thisisanumber.Thisisanumber.Thisisanumber."),
"--------",paste("Multiple-vlaueoptions:longtextlongtextlongtext",
"longtextlongtextlongtextlongtextlongtext"),
"array=f@",paste("Thisisanarray.Thisisanarray.Thisisanarray.",
"Thisisanarray.Thisisanarray.Thisisanarray."),
"hash=s%",paste("Thisisahash.Thisisahash.Thisisahash.",
"Thisisahash.Thisisahash.Thisisahash."),
"-------","Otheroptions:"
)
Usage:Rscriptfoo.R[options]
Binaryoptions:
--verbose,-no-verbose
Whethershowmessages
[default:off]
--flag,-f
anon-senseoption
Single-valueoptions:
--count,-cinteger
Thisisacount.Thisisacount.Thisisacount.Thisisacount.Thisis
acount.Thisisacount.
[default:1]
--number,-nnumeric
Thisisanumber.Thisisanumber.Thisisanumber.Thisisanumber.This
isanumber.Thisisanumber.
Multiple-vlaueoptions:longtextlongtextlongtextlongtextlongtextlong
textlongtextlongtext
--array,-a[numeric,...]
Thisisanarray.Thisisanarray.Thisisanarray.Thisisanarray.This
isanarray.Thisisanarray.
[default:0.1,0.2]
--hash{name=character,...}
Thisisahash.Thisisahash.Thisisahash.Thisisahash.Thisisa
hash.Thisisahash.
Otheroptions:
--help
Printhelpmessageandexit.
--version
Printversioninformationandexit.
Andthetwo-columnstyleforthegroupedoptions.
GetoptLong.options(help_style="two-column")
GetoptLong{
...
}
Usage:Rscriptfoo.R[options]
Binaryoptions:
--verbose,-no-verboseWhethershowmessages
[default:off]
--flag,-fanon-senseoption
Single-valueoptions:
--count,-cThisisacount.Thisisacount.Thisisacount.Thisisa
[type:int]count.Thisisacount.Thisisacount.
[default:1]
--number,-nThisisanumber.Thisisanumber.Thisisanumber.Thisis
[type:num]anumber.Thisisanumber.Thisisanumber.
Multiple-vlaueoptions:longtextlongtextlongtextlongtextlongtextlong
textlongtextlongtext
--array,-aThisisanarray.Thisisanarray.Thisisan
[type:[num,...]]array.Thisisanarray.Thisisanarray.Thisis
anarray.
[default:0.1,0.2]
--hashThisisahash.Thisisahash.Thisisahash.This
[type:{name=chr,...}]isahash.Thisisahash.Thisisahash.
Otheroptions:
--helpPrinthelpmessageandexit.
--versionPrintversioninformationandexit.
TheglobaloptionGetoptLong.options$help_widthcontrolsthemaximalwidthoftheusagemessage.
Thespecificationcanalsobesetasatemplatewhichprovidesmoreflexibilitiesfortheusagemessage.Hereoptionspecificationsaremakedby<>wherethespecificationswillbeextractedandthetextwillbereplacedbytheoptiondescription.ThemarkcanbesetbyGetoptLong.options$template_tagglobaloption.
Theoptiondescriptionshavedifferentwidths.Toproperlyalignthetext,youneedtomanuallyadjustthewidth(spacesarefilledifthewidthislargerthantheoptiondescription)bysettingopt_widthparameterviatemplate_controlargument.Seethefollowingexample.
GetoptLong("
Thisisademonstrationofusingtemplateastheoptionspecification.
Usage:Rscriptfoo.R[options]
Binaryoptions:
Whethershowmessages
Anon-senseoption
Single-valueoptions:
Thisisacount.Thisisacount.
Thisisanumber.Thisisanumber.
Multiple-vlaueoptions:
Thisisanarray.Thisisanarray.
Thisisahash.Thisisahash.
Questions,pleasecontactyour.name@email
",template_control=list(opt_width=c(verbose=23,flag=23,
count=22,number=22,
array=30,hash=30)
))
Thisisademonstrationofusingtemplateastheoptionspecification.
Usage:Rscriptfoo.R[options]
Binaryoptions:
--verbose,-no-verboseWhethershowmessages
--flag,-fAnon-senseoption
Single-valueoptions:
--count,-cintegerThisisacount.Thisisacount.
--number,-nnumericThisisanumber.Thisisanumber.
Multiple-vlaueoptions:
--array,-a[numeric,...]Thisisanarray.Thisisanarray.
--hash{name=character,...}Thisisahash.Thisisahash.
Questions,pleasecontactyour.name@email
Iftheoptionexplanationliesinmorethanonelines,infrontfromthesecondline,youshouldaddataginformofwheretagistheoptionnameofthecurrentoptionblock,sothatproperspacesinfrontofthetextcanbecalculatedandthetextwillbeproperlyaligned.Seethefollowingexample:
GetoptLong("
Usage:Rscriptfoo.R[options]
Thisisacount.Thisisacount.Thisisacount.
Thisisacount.Thisisacount.
Thisisanumber.Thisisanumber.Thisisanumber.
Thisisanumber.Thisisanumber.
",template_control=list(opt_width=c(count=28,number=28))
)
Usage:Rscriptfoo.R[options]
--count,-c[integer,...]Thisisacount.Thisisacount.Thisisacount.
Thisisacount.Thisisacount.
--number,-nnumericThisisanumber.Thisisanumber.Thisisanumber.
Thisisanumber.Thisisanumber.
Versionoption
versionisalsoareservedoption.
VersionshouldbestoredinavariableVERSIONbeforethecallofGetoptLong(),then--versionprintsthecorrespondingversionvalue.
VERSION="0.0.1"
GetoptLong(
"tag=i","...",
)
~\>Rscriptfoo.R--version
0.0.1
ConfiguringGetopt::Long
ConfigurationofGetopt::LongcanbesetbyGetoptLong.options("config"):
GetoptLong.options("config"="bundling")
GetoptLong.options("config"=c("no_ignore_case","bundling"))
Withdifferentconfigurations,itcansupportmoretypesofoptionspecifications:
-a-b-c-abc
-s24-s24-s=24
PleaserefertowebsiteofGetopt::Longformoreinformation.
SpecifypathofPerlincommandline
InsomeconditionsthatpathofbinaryPerlisnotinthePATHenvironmentvariableandyoudonothavepermissiontomodifyPATH.YoucanspecifyyourPerlpathfromcommandlinelike:
~\>Rscriptfoo.R-a-b-c--/your/perl/bin/perl
Sinceargumentsfollowingafter--willbeignoredbyGetopt::Long,wetakethefirstargumentnextto--asthepathofuser-specifiedPerlpath.
Specifycommand-lineoptionswithinRsession
WheninaninteractiveRsession,argumentscanbesetwhencallingsource_script(),soitwouldbeconvinienttoloadexternalRscriptswithdifferentcomand-linearguments.E.g.:
source_script("foo.R",argv_str="--cutoff0.01--inputfile=foo.txt--verbose")
Sessioninfo
sessionInfo()
Rversion4.0.2(2020-06-22)
Platform:x86_64-apple-darwin17.0(64-bit)
Runningunder:macOSCatalina10.15.5
Matrixproducts:default
BLAS:/Library/Frameworks/R.framework/Versions/4.0/Resources/lib/libRblas.dylib
LAPACK:/Library/Frameworks/R.framework/Versions/4.0/Resources/lib/libRlapack.dylib
locale:
[1]C/en_GB.UTF-8/en_GB.UTF-8/C/en_GB.UTF-8/en_GB.UTF-8
attachedbasepackages:
[1]statsgraphicsgrDevicesutilsdatasetsmethodsbase
otherattachedpackages:
[1]GetoptLong_1.0.5knitr_1.30
loadedviaanamespace(andnotattached):
[1]compiler_4.0.2rjson_0.2.20magrittr_2.0.1
[4]htmltools_0.5.0tools_4.0.2GlobalOptions_0.1.2
[7]yaml_2.2.1crayon_1.3.4stringi_1.5.3
[10]rmarkdown_2.5stringr_1.4.0digest_0.6.27
[13]xfun_0.19rlang_0.4.8evaluate_0.14