[R] working with list

Hiroyuki Kawakatsu kawa at aris.ss.uci.edu
Wed Feb 19 15:47:06 CET 2003


i have two questions:
(1) lookup: given a list of 'strings' in a list, i want to know the index
of a given string in the list. if the string is not in the list, the index
can be 0 or length()+1. for example, suppose i have
names <- c("dog", "cat", "pig", "fish");
then i want
lookup(names, "cat") to return 2 and
lookup(names, "ant") to return 0 (or 5)

i am currently doing this in a for loop with a break using identical().
however, since i call this function repeatedly, i am wondering whether
there is a more efficient way of doing this.

(2) combining lists: when lists are combined, the higher level list
structure appears to be lost. what i mean is, suppose i have two lists
with the same structure
a <- list(name="foo", year=1989, grade="A");
b <- list(name="bar", year=2000, grade="B+");
then when i combine the two lists into one
ab <- c(a, b);
length(ab) returns length(a)+length(b), not 2.

given a list of lists, is there any way i can loop through each
list and work with the named components in each list? it seems that i need
to know the length of each list and the order each component appears in
the list to work with the combined list. the solution i am currently using
is not to combine the list but use ... in a function argument and to
extract each list by:

foo <- function(...) {
   args <- list(...);
   for (i in 1:length(args)) {
      #extract i-th list
      tmp <- args[[i]];

Time series regression studies give no sign of converging toward the
truth. (Phillip Cagan)

More information about the R-help mailing list