[R] working with list

kjetil brinchmann halvorsen kjetil at entelnet.bo
Wed Feb 19 17:40:03 CET 2003


On 19 Feb 2003 at 6:46, Hiroyuki Kawakatsu wrote:

Is this what you want:

> names <- c("dog",
+ "cat", "pig", "fish");
> names
[1] "dog"  "cat"  "pig"  "fish"
> which(names=="cat")
[1] 2
> which(names=="ant")
numeric(0)
> lookup <- function(db, item) {
+    res <- which(db==item)
+    if (length(res)==0) res <- 0
+    res}
> lookup(names, "cat")
[1] 2
> lookup(names, "ant")
[1] 0


> 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.

so you want ab <- list(a,b)

> 
> 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