[21] "of" "only" "one" "line" "and"
[26] "one" "item" "so" "this" "is"
[31] "redundant" "but" "this" "notation" "helps"
[36] "to" "read" "voluminous" "output" "that"
[41] "consists" "of" "many" "items" "spread"
[46] "over" "many" "lines" "for" "example"
[51] "if" "there" "were" "two" "rows"
[56] "of" "output" "with" "six" "items"
[61] "per" "row" "the" "second" "row"
[66] "would" "be" "labeled"
The list operations in lines 4 through 8 build up our main variable, a list
wl(forword list). We loop through all the words from our long line, withwrd
being the current one.
Let’s see what happens with the code in line 7 wheni=4, so thatwrd =
"that"in our example filetestconcorda.txt. At this point,wl[["that"]]will not
yet exist. As mentioned, R is set up so that in such a case,wl[["that"]] = NULL,
which means in line 7, we can concatenate it! Thuswl[["that"]]will become
the one-element vector (4). Later, wheni=40,wl[["that"]]will become
(4,40), representing the fact that words 4 and 40 in the file are both"that".
Note how convenient it is that list indexing can be done through quoted
strings, such as inwl[["that"]].
An advanced, more elegant version of this code uses R’ssplit()func-
tion, as you’ll see in Section 6.2.2.
4.3 Accessing List Components and Values.......................................
If the components in a list do have tags, as is the case withname,salary, and
unionforjin Section 4.1, you can obtain them vianames():
> names(j)
[1] "name" "salary" "union"
To obtain the values, useunlist():
> ulj <- unlist(j)
> ulj
name salary union
"Joe" "55000" "TRUE"
> class(ulj)
[1] "character"
The return value ofunlist()is a vector—in this case, a vector of charac-
ter strings. Note that the element names in this vector come from the com-
ponents in the original list.
Lists 93