[R] working with list

Thomas W Blackwell tblackw at umich.edu
Wed Feb 19 16:27:04 CET 2003


Three quick answers:

(1) function  match("cat", names, 0)  would return 2.
(2) syntax  list(a,b)  would return a list of lists with length 2.
(3) syntax  unlist(lapply(ab, function(x) x[["year"]]))
    would return a vector equal to  c(1989,2000).

See the interactive help for each of these functions.

-  tom blackwell  -  u michigan medical school  -  ann arbor  -



On Wed, 19 Feb 2003, Hiroyuki Kawakatsu wrote:

> hi,
>
> 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]];
>    }
> }
>
> h.
> --------------------------------------------------------------------
> Time series regression studies give no sign of converging toward the
> truth. (Phillip Cagan)
>
> ______________________________________________
> R-help at stat.math.ethz.ch mailing list
> http://www.stat.math.ethz.ch/mailman/listinfo/r-help
>




More information about the R-help mailing list