5

Lists and Cell Arrays

In both R and MATLAB, a matrix or vector can only hold a set of values of the same type,

for example ﬂoating-point values, integers, logical values, characters, etc. Sometimes it is

convenient to build a more ge neral object w hich can contain values of diﬀerent types. Both

platforms provide ways of doing this. In R, lists are used, while in MATL AB, cell arrays

are used (but also see MATLAB structs in Section 3.8.3 ). As with matrices and vectors,

in R, a list is fundamentally a vector object (from which you can build matrices), while in

MATLAB a cell array is fundamentally a matrix (which may be equivalent to a vector if it

happens to have only one row or co lumn).

5.1 Creating lists and cell arrays

Let us create a list or cell array containing four elements: (1) a vector V1 containing the

values 4, 8, and 15; (2) a variable V2 containing the string “hello”; (3) a 2 ×3 matrix V3 of

random values; and (4) the variable V4 containing the logical value TRUE. We will build

the object in two forms: ﬁrst, as a vector tmp, and second, as a 2 × 2 matrix tmpA (with

the four elements arranged down the ﬁrst column and then the second column).

R

First set up the temporary variable s:

R

V1 = c(4,8,15); V2 = 'hello'

V3 = matrix(runif(6), nrow=2); V4 = TRUE

As with vectors, the elements of lists can be referred to by number, but if names a re

provided, then they may also be us e d to acce ss elements of the list. To create our e xample

list in vector form without names, you can use tmpNoNames = list(V1, V2, V3, V4). If

you wish to pr ovide names as well, you can instead use tmp = list(foo=V1, bar=V2,

baz=V3, quu x=V4). As shown in the example, the names of the list elements do not need

to match the variables originally holding their values.

To create the list as a 2 ×2 matrix, you can either reshape a vector, or use matrix. If

you have already created the vector list above, you can either do tmpA = tmp; dim(tmpA)

= c(2,2) or else tmpA = mat rix(tmp, nrow=2). Note that both of these methods strip

out names of elements that were present in the original list tmp. You can restore them via

names(tmpA) = names(tmp). In general, the same mechanisms for working with the names

of elements of a vector described in Section 3.8.1 can be used with lists.

An a lternative way to create a list is to ﬁrst c reate an empty list of the desired le ngth

and then ﬁll in its elements, as follows.

55

Get *R and MATLAB* now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.