Accessing List Components and Values
If the components in a list do have tags, as is the case with name
, salary
, and union
for j
in Section 4.1, you can obtain them via names()
:
> names(j) [1] "name" "salary" "union"
To obtain the values, use unlist()
:
> ulj <- unlist(j) > ulj name salary union "Joe" "55000" "TRUE" > class(ulj) [1] "character"
The return value of unlist()
is a vector—in this case, a vector of character strings. Note that the element names in this vector come from the components in the original list.
On the other hand, if we were to start with numbers, we would get numbers.
> z <- list(a=5,b=12,c=13) > y <- unlist(z) > class(y) [1] "numeric" > y a b c 5 12 13
So the output of unlist()
in this case was a numeric vector. What about ...
Get The Art of R Programming 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.