Chapter 14
Named lists and strings
14.1 Named lists
Manygretlcommandstakeoneormore listsofseries as arguments. Tomake thiseasier to handle
inthe contextofcommandscripts,andinparticular withinuser-definedfunctions,gretloffersthe
possibilityofnamedlists.
Creatingandmodifyingnamedlists
Anamed listis created using the keyword list, followed by the name of the list, an equals sign,
andanexpressionthatformsalist. Themostbasicsortofexpressionthatworksinthiscontextis
aspace-separatedlistofvariables,giveneitherbynameorbyIDnumber. Forexample,
list xlist = 1 2 3 4
list reglist = income price
Notethatthevariablesinquestionmustbe ofthe seriestype.
Twoabbreviationsareavailable indefininglists:
 You can use the wildcard character, “*”, to create a list ofvariables byname. For example,
dum*canbeusedto indicateallvariableswhose names beginwithdum.
 Youcanusetwo dots toindicate arangeofvariables. Forexample income..priceindicates
the set ofvariables whose ID numbers are greater than or equal to thatof income and less
thanorequalto thatofprice.
Inadditiontherearetwo specialforms:
 Ifyouusethe keywordnullonthe right-handside, yougetanemptylist.
 If you use the keyword dataset on the right, you get a list containing all the series in the
currentdataset(exceptthe pre-definedconst).
The name of the list must start with aletter, and must be composed entirelyof letters, numbers
or theunderscore character. The maximumlengthofthe nameis 31 characters; listnames cannot
containspaces.
Once anamedlisthas beencreated, it willbe “remembered” for the durationofthe gretlsession
(unlessyoudeleteit),andcanbeusedinthecontextofanygretlcommandwherealistofvariables
is expected. One simpleexample is thespecificationofalistofregressors:
list xlist = x1 x2 x3 x4
ols y 0 xlist
Togetridofalist,youusethe followingsyntax:
list xlist delete
110
How to convert pdf into powerpoint slides - SDK control service:C# Create PDF from PowerPoint Library to convert pptx, ppt to PDF in C#.net, ASP.NET MVC, WinForms, WPF
Online C# Tutorial for Creating PDF from Microsoft PowerPoint Presentation
www.rasteredge.com
How to convert pdf into powerpoint slides - SDK control service:VB.NET Create PDF from PowerPoint Library to convert pptx, ppt to PDF in vb.net, ASP.NET MVC, WinForms, WPF
VB.NET Tutorial for Export PDF file from Microsoft Office PowerPoint
www.rasteredge.com
Chapter14. Namedlists andstrings
111
Be careful: delete xlistwilldeletethe series containedinthe list,soitimpliesdataloss(which
may not be what you want). On the other hand, list xlist delete will simply “undefine” the
xlistidentifier; theseriesthemselveswillnotbe affected.
Similarly, toprintthe namesofthe members ofalistyouhave toinvertthe usualprintcommand,
as in
list xlist print
Ifyoujustsayprint xlist the listwill be expandedandthe values of allthe member series will
be printed.
Listscanbe modifiedin various ways. To redefine anexistinglistaltogether, use the same syntax
as for creatingalist. Forexample
list xlist = 1 2 3
xlist = 4 5 6
Afterthe secondassignment,xlist contains justvariables 4, 5and6.
To append or prepend variables to anexisting list, we can make use ofthe factthat anamedlist
standsinfor a“longhand” list. For example,we cando
list xlist = xlist 5 6 7
xlist = 9 10 xlist 11 12
Another optionfor appendingaterm(oralist)toanexistinglististo use +=,asin
xlist += cpi
Todropavariablefromalist,use-=:
xlist -= cpi
Inmostcontextswherelistsareusedingretl,itisexpectedthattheydonotcontainanyduplicated
elements. If you form anewlist bysimple concatenation, asin list L3 = L1 L2 (where L1 and
L2 areexistinglists),it’spossiblethattheresultmaycontainduplicates. To guardagainstthisyou
canformanewlistastheunionoftwo existingones:
list L3 = L1 || L2
TheresultisalistthatcontainsallthemembersofL1,plusanymembersofL2thatarenotalready
inL1.
Inthe same vein,youcanconstructanewlistasthe intersectionoftwoexistingones:
list L3 = L1 && L2
HereL3containsalltheelementsthatare presentinbothL1 andL2.
Youcanalsosubtractone listfromanother:
list L3 = L1 - L2
Theresultcontains allthe elementsofL1thatare notpresentinL2.
SDK control service:C# PowerPoint - How to Process PowerPoint
control, developers are able to split a PowerPoint into two or more It enables you to move out useless PowerPoint document pages C# Codes to Sort Slides Order.
www.rasteredge.com
SDK control service:VB.NET PowerPoint: Process & Manipulate PPT (.pptx) Slide(s)
split one PPT (.pptx) document file into smaller sub library SDK, this VB.NET PowerPoint processing control & profession imaging controls, PDF document, image
www.rasteredge.com
Chapter14. Namedlists andstrings
112
Listsand matrices
Another way of forming a list is by assignment from a matrix. The matrix in question must be
interpretable as avector containing IDnumbers of dataseries. Itmaybe either arowor acolumn
vector, and eachof its elements musthave an integer part that is no greater than the number of
variablesinthedataset. For example:
matrix m = {1,2,3,4}
list L = m
TheaboveisOKprovidedthe datasetcontainsatleast4 variables.
Queryingalist
Youcandetermine thenumberofvariablesorelementsinalistusingthefunctionnelem().
list xlist = 1 2 3
nl = nelem(xlist)
The(scalar)variablenl willbeassignedavalue of3 since xlist contains3 members.
You can determine whether a given series is a member of a specified list using the function
inlist(), as in
scalar k = inlist(L, y)
whereLisalistandyaseries. TheseriesmaybespecifiedbynameorIDnumber. Thereturnvalue
is the(1-based)positionofthe seriesinthelist,orzero ifthe seriesisnotpresentinthe list.
Generatinglistsoftransformedvariables
Givenanamed listofseries,youare able togenerate listsoftransformationsofthese seriesusing
thefunctionslog,lags,diff,ldiff,sdiffordummify. Forexample
list xlist = x1 x2 x3
list lxlist = log(xlist)
list difflist = diff(xlist)
Whengeneratingalistoflags inthisway,youspecifythe maximumlagorderinside theparenthe-
ses,beforethe listnameandseparatedbyacomma. For example
list xlist = x1 x2 x3
list laglist = lags(2, xlist)
or
scalar order = 4
list laglist = lags(order, xlist)
Thesecommandswillpopulatelaglistwiththespecifiednumberoflagsofthevariablesinxlist.
Youcan give the name of asingle series inplace of alist as the second argumentto lags: this is
equivalenttogivingalistwithjustonemember.
Thedummifyfunctioncreatesasetofdummyvariablescodingforallbutoneofthe distinctvalues
taken on by the original variable, which should be discrete. (The smallest value is taken as the
omittedcatgory.) Likelags, this functionreturnsalisteveniftheinputisasingle series.
SDK control service:VB.NET PowerPoint: Merge and Split PowerPoint Document(s) with PPT
sample code in VB.NET to finish PowerPoint document splitting &ltsummary> ''' Split a document into 2 sub Note: If you want to see more PDF processing functions
www.rasteredge.com
SDK control service:VB.NET PowerPoint: Extract & Collect PPT Slide(s) Using VB Sample
you want to combine these extracted slides into a new please read this VB.NET PowerPoint slide processing & profession imaging controls, PDF document, image to
www.rasteredge.com
Chapter14. Namedlists andstrings
113
Another usefuloperationyoucanperformwithlists is creatinginteractionvariables. Suppose you
have adiscretevariable x
i
,takingvalues from1to n andavariablez
i
,whichcouldbe continuous
or discrete. Inmanycases, youwantto“split” z
i
intoasetofn variablesviatherule
z
j
i
(
z
i
when x
i
j
0
otherwise;
inpractice,youcreatedummiesforthex
i
variable firstandthenyoumultiplythemallbyz
i
;these
are commonlycalledthe interactionsbetweenx
i
andz
i
. Ingretlyoucando
list H = D ^ Z
where Disalistofdiscrete series(orasinglediscrete series), Zis alist(or asingle series)
1
;allthe
interactions willbecreatedandlistedtogetherunder thenameH.
Anexample isprovidedinscript14.1
Generatingseriesfromlists
There are various ways ofretrieving or generating individual series froma named list. The most
basic methodisindexinginto thelist. Forexample,
series x3 = Xlist[3]
will retrieve the third element of the list Xlist under the name x3 (or will generate an error if
Xlisthasless thenthree members).
In addition gretl offers several functions that apply to a list and return a series. In most cases,
thesefunctions also applyto single series and behave asnaturalextensionswhenappliedto lists,
butthisisnotalwaysthe case.
Forrecognizingandhandlingmissingvalues,gretloffersseveralfunctions(seetheGretlCommand
Reference for details). In this context, it is worth remarking that the ok() function can be used
withalistargument. Forexample,
list xlist = x1 x2 x3
series xok = ok(xlist)
After these commands, the series xok willhave value 1 for observations where none ofx1, x2, or
x3 has amissingvalue,andvalue0 foranyobservationswhere this conditionisnotmet.
The functionsmax,min,mean, sd,sumandvar behave “horizontally” ratherthan“vertically” when
theirargumentis alist. Forinstance, thefollowingcommands
list Xlist = x1 x2 x3
series m = mean(Xlist)
produce aseriesmwhose i-thelementistheaverageofx
1;i
;x
2;i
andx
3;i
;missingvalues,ifany,are
implicitlydiscarded.
Inaddition,gretlprovidesthreefunctionsforweightedoperations:wmean,wsdandwvar. Consider
as an illustrationTable14.1: the first three columns are GDP per capita for France, Germanyand
Italy; columns4 to6 containthepopulationforeachcountry. Ifwewantto computeanaggregate
indicator ofpercapitaGDP, allwe have todo is
list Ypc = YpcFR YpcGE YpcIT
list N = NFR NGE NIT
y = wmean(Ypc, N)
1
Warning: thisconstructdoesnotworkifneitherDnorZareofthethelisttype.
SDK control service:VB.NET PowerPoint: Use PowerPoint SDK to Create, Load and Save PPT
guide for PPT document, we divide this page into three parts in VB.NET to create an empty PowerPoint file with or local file and get the exact PPT slides number;
www.rasteredge.com
SDK control service:VB.NET PowerPoint: Convert & Render PPT into PDF Document
Using this VB.NET PowerPoint to PDF converting demo code below, you can easily convert all slides of source PowerPoint document into a multi-page PDF file.
www.rasteredge.com
Chapter14. Namedlists andstrings
114
Example14.1: Usageofinteractionlists
Input:
open mroz87.gdt --quiet
# the coding below makes it so that
# KIDS = 0 -> no kids
# KIDS = 1 -> young kids only
# KIDS = 2 -> young or older kids
series KIDS = (KL6 > 0) + ((KL6 > 0) || (K618 > 0))
list D = CIT KIDS # interaction discrete variables
list X = WE WA
# variables to "split"
list INTER = D ^ X
smpl 1 6
print D X INTER -o
Output(selectedportions):
CIT
KIDS
WE
WA
WE_CIT_0
1
0
2
12
32
12
2
1
1
12
30
0
3
0
2
12
35
12
4
0
1
12
34
12
5
1
2
14
31
0
6
1
0
12
54
0
WE_CIT_1
WA_CIT_0
WA_CIT_1
WE_KIDS_0
WE_KIDS_1
1
0
32
0
0
0
2
12
0
30
0
12
3
0
35
0
0
0
4
0
34
0
0
12
5
14
0
31
0
0
6
12
0
54
12
0
WE_KIDS_2
WA_KIDS_0
WA_KIDS_1
WA_KIDS_2
1
12
0
0
32
2
0
0
30
0
3
12
0
0
35
4
0
0
34
0
5
14
0
0
31
6
0
54
0
0
soforexample
y
1996
114:959830:635124:682034:771119:356890:372
59830:63582034:77156890:372
120:163
See theGretlCommandReference for moredetails.
SDK control service:VB.NET PowerPoint: Sort and Reorder PowerPoint Slides by Using VB.
clip art or screenshot to PowerPoint document slide large amount of robust PPT slides/pages editing powerful & profession imaging controls, PDF document, image
www.rasteredge.com
SDK control service:VB.NET PowerPoint: Add Image to PowerPoint Document Slide/Page
to add, insert or delete any certain PowerPoint slide without a multi-page PPT document into 2, 4, 6 powerful & profession imaging controls, PDF document, tiff
www.rasteredge.com
Chapter14. Namedlists andstrings
115
YpcFR
YpcGE
YpcIT
NFR
NGE
NIT
1997
114.9
124.6
119.3
59830.635
82034.771
56890.372
1998
115.3
122.7
120.0
60046.709
82047.195
56906.744
1999
115.0
122.4
117.8
60348.255
82100.243
56916.317
2000
115.6
118.8
117.2
60750.876
82211.508
56942.108
2001
116.0
116.9
118.1
61181.560
82349.925
56977.217
2002
116.3
115.5
112.2
61615.562
82488.495
57157.406
2003
112.1
116.9
111.0
62041.798
82534.176
57604.658
2004
110.3
116.6
106.9
62444.707
82516.260
58175.310
2005
112.4
115.1
105.1
62818.185
82469.422
58607.043
2006
111.9
114.2
103.3
63195.457
82376.451
58941.499
Table14.1:GDPpercapitaandpopulationin3Europeancountries(Source: Eurostat)
14.2 Named strings
For some purposesitmaybe usefulto save astring (thatis,asequence ofcharacters) as anamed
variable thatcanbe reused.
Someexamplesofthe definitionofastringvariableareshownbelow.
string s1 = "some stuff I want to save"
string s2 = getenv("HOME")
string s3 = s1 + 11
Thefirstfieldafterthetype-namestringisthe nameunderwhichthestringshouldbesaved,then
comesanequalssign,thencomesaspecificationofthestringtobesaved. Thiscanbethekeyword
null,to produce anemptystring,ormaytake anyofthefollowingforms:
 astringliteral(enclosedindoublequotes); or
 thename ofanexistingstringvariable;or
 afunctionthatreturnsastring(see below);or
 anyoftheabove followedby+ andanintegeroffset.
The role of the integer offset is to use a substringof the preceding element, starting at the given
character offset. Anemptystringisreturnedifthe offsetisgreaterthanthelengthofthe string in
question.
Toaddto theendofanexistingstring youcanuse theoperator~=,asin
string s1 = "some stuff I want to "
string s1 ~= "save"
or youcanuse the~ operator to jointwoormore strings,asin
string s1 = "sweet"
string s2 = "Home, " ~ s1 ~ " home."
Note that when you define a string variable using a string literal, no characters are treated as
“special” (other thanthe double quotes thatdelimitthe string). Specifically, the backslash is not
usedas anescapecharacter. So,forexample,
SDK control service:C# PowerPoint: C# Guide to Add, Insert and Delete PPT Slide(s)
empty page and insert it into an existing view detailed guide for each PowerPoint slide processing powerful & profession imaging controls, PDF document, tiff
www.rasteredge.com
SDK control service:C# PowerPoint: C# Codes to Combine & Split PowerPoint Documents
2 sub-documents, if you need to split PowerPoint into 4, 6 &ltsummary> /// Split a document into 2 sub powerful & profession imaging controls, PDF document, tiff
www.rasteredge.com
Chapter14. Namedlists andstrings
116
string s = "\"
is avalidassignment,producingastringthatcontains asingle backslashcharacter. Ifyouwishto
use backslash-escapes to denotenewlines, tabs, embeddeddouble-quotes andso on, use sprintf
instead.
The sprintf command can also be used to define a string variable. This command works in
exactly the same way as the printf command except thatthe “format” string must be preceded
by anidentifier: either the name of anexisting string variable or a new name to whichthe string
shouldbe assigned. Forexample,
scalar x = 8
sprintf foo "var%d", x
Stringvariablesandstring substitution
String variables can be used in two ways in scripting: the name of the variable can be typed “as
is”, or it maybe preceded bythe “at” sign, @. Inthe firstvariant the named string istreated as a
variable in its own right, while the second calls for “string substitution”. The context determines
whichofthese variantsisappropriate.
Inthe followingcontexts the names of string variables shouldbe given in plain form(withoutthe
“at” sign):
 Whensuchavariableappearsamongthe argumentstothe commandsprintforsprintf.
 Whensuchavariableis givenasthe argumentto afunction.
 Onthe right-handsideofastring assignment.
Hereisanillustrationofthe useofanamedstringargumentwithprintf:
? string vstr = "variance"
Generated string vstr
? printf "vstr: %12s\n", vstr
vstr:
variance
String substitution can be used in contexts where a string variable is not acceptable as such. If
gretl encounters the symbol@ followed directly bythe name of astring variable, this notation is
treated as a“macro”: the valueofthe variable issustituted literallyintothe commandline before
theregular parsingofthecommandiscarriedout.
One commonuseofstringsubstitutioniswhenyouwanttoconstructandusethenameofaseries
programatically. Forexample, suppose youwanttocreate 10 randomnormalseries namednorm1
tonorm10. Thiscanbeaccomplishedas follows.
string sname = null
loop i=1..10
sprintf sname "norm%d", i
series @sname = normal()
endloop
Note that plain sname could not be used in the second line within the loop: the effect would be
to attempt to overwrite the string variable named sname with a series of the same name. What
we want isfor the currentvalue ofsname to be dumped directly into the commandthatdefines a
series,andthe “@” notationachievesthat.
Another typical use of string substitution is when you want the options used with a particular
commandto varydependingonsomecondition. For example,
Chapter14. Namedlists andstrings
117
function void use_optstr (series y, list xlist, int verbose)
string optstr = verbose ? "" : "--simple-print"
ols y xlist @optstr
end function
open data4-1
list X = const sqft
use_optstr(price, X, 1)
use_optstr(price, X, 0)
When printing the value of a string variable using the print command, the plain variable name
shouldgenerallybeused, as in
string s = "Just testing"
print s
Thefollowingvariantisequivalent,thoughclumsy.
string s = "Just testing"
print "@s"
Butnotethatthis nextvariantdoes somethingquitedifferent.
string s = "Just testing"
print @s
Afterstringsubstitution, theprintcommandreads
print Just testing
whichattemptsto printthevaluesoftwovariables,Justandtesting.
Built-instrings
Apart from anystrings thatthe user may define, some string variables are defined bygretlitself.
Thesemaybeusefulforpeoplewritingfunctionsthatincludeshellcommands. Thebuilt-instrings
are as showninTable14.2.
gretldir
the gretlinstallationdirectory
workdir
user’scurrentgretlworkingdirectory
dotdir
the directorygretluses for temporaryfiles
gnuplot
pathto, or name of,thegnuplot executable
tramo
pathto, or name of,thetramoexecutable
x12a
pathto, or name of,thex-12-arimaexecutable
tramodir
tramodatadirectory
x12adir
x-12-arimadatadirectory
Table14.2:Built-instringvariables
To access these asordinarystringvariables,prepend adollar sign (as in$dotdir); to use them in
string-substitutionmode, prependtheat-sign(@dotdir).
Reading strings fromtheenvironment
Inaddition, itis possibleto readinto gretl’snamed strings,valuesthatare definedinthe external
environment. To do this you use the function getenv, which takes the name of an environment
variable asitsargument. Forexample:
Chapter14. Namedlists andstrings
118
? string user = getenv("USER")
Generated string user
? string home = getenv("HOME")
Generated string home
? printf "%s’s home directory is %s\n", user, home
cottrell’s home directory is /home/cottrell
Tocheckwhether yougotanon-emptyvaluefromagivencalltogetenv,youcanusethe function
strlen,whichretrieves thelengthofthe string,asin
? string temp = getenv("TEMP")
Generated string temp
? scalar x = strlen(temp)
Generated scalar x = 0
Capturing stringsviatheshell
Ifshellcommandsare enabledingretl,youcancapturetheoutputfromsuchcommandsusingthe
syntax
stringstringname= $(shellcommand)
Thatis,youenclose ashellcommandinparentheses,precededbyadollarsign.
Reading fromafileintoastring
Youcanreadthecontentofafile into astringvariableusingthesyntax
stringstringname= readfile(filename)
Thefilename fieldmaybe givenasastringvariable. Forexample
? sprintf fname "%s/QNC.rts", $x12adir
Generated string fname
? string foo = readfile(fname)
Generated string foo
Morestring functions
Gretl offers several functions for creating or manipulating strings. You can find these listedand
explainedinthe FunctionReferenceunderthe categoryStrings.
Chapter 15
Matrix manipulation
Together with the other two basic types of data (series and scalars), gretloffers a quite compre-
hensive array of matrix methods. This chapter illustrates the peculiarities of matrix syntax and
discussesbrieflysome ofthe morecomplexmatrixfunctions. For afulllistingofmatrixfunctions
andacomprehensive accountoftheirsyntax,please referto theGretlCommandReference.
15.1 Creating matrices
Matricescanbecreatedusinganyofthesemethods:
1. By directspecificationofthe scalarvaluesthatcompose thematrix — innumericalform, by
reference topre-existingscalarvariables,orusingcomputedvalues.
2. Byprovidingalistofdataseries.
3. Byprovidinganamed list ofseries.
4. Usingaformulaofthesamegeneraltypethatisusedwiththegenrcommand,wherebyanew
matrixisdefinedinterms ofexistingmatricesand/or scalars,orviasomespecialfunctions.
Tospecifyamatrixdirectlyintermsof scalars,the syntaxis,forexample:
matrix A = { 1, 2, 3 ; 4, 5, 6 }
The matrix is definedby rows; the elements on each roware separated bycommas and the rows
are separatedbysemi-colons. The whole expressionmustbewrappedinbraces. Spaceswithinthe
bracesare not significant. The above expressiondefines a23matrix. Each elementshouldbe a
numericalvalue, the name ofascalar variable, or anexpressionthatevaluates toascalar. Directly
after theclosingbraceyoucanappendasinglequote (’)to obtainthe transpose.
Tospecifyamatrixintermsof dataseries the syntaxis,forexample,
matrix A = { x1, x2, x3 }
where the names of the variables are separated bycommas. Besides names of existing variables,
youcanuse expressionsthatevaluate toaseries. Forexample, givenaseriesx youcoulddo
matrix A = { x, x^2 }
Eachvariable occupies acolumn(andthere can onlybe one variable per column). Youcannotuse
thesemicolonasarowseparator inthiscase: ifyouwanttheseriesarrangedinrows, appendthe
transpose symbol. Therange ofdatavaluesincludedinthe matrixdependsonthe currentsetting
ofthe samplerange.
Insteadofgivinganexplicitlistofvariables,youmayinsteadprovide the name ofa savedlist (see
Chapter14),asin
119
Documents you may be interested
Documents you may be interested