What about ...

> unlist(lis)[which(unlist(lis)=="next")+1]
[1] "want1" "want2"

... to avoid the loop in sapply?


Richard A. O'Keefe wrote:


Chris Knight <[EMAIL PROTECTED]> has
        
        lis<-list(c("a","b","next","want1","c"),c("d", "next", "want2", "a"))
        
and wants c("want1","want2")


Step 1: inx <- sapply(lis, function(x) which(x == "next")) + 1 ==> 4 3

Step 2:
   sapply(1:length(lis), function(i) lis[[i]][inx[i]])
==> "want1" "want2"

Think about this for a bit and restructure it:

sapply(1:length(lis), function (i) {v <- lis[[i]]; v[which(v=="next")+1]})

Wrap it up:

   after <- function(lis, what="next") {
        sapply(1:length(lis), function (i) {
            v <- lis[[i]]
            v[which(v == what)+1]
        })
   }

Of course, from my point of view, a call to sapply() *is* a loop, just
packaged slightly differently.  I think this is reasonably clear.

--------------------------------------------------------
Peter Wolf
Department of economics
University of Bielefeld
[EMAIL PROTECTED]

______________________________________________
[EMAIL PROTECTED] mailing list
https://www.stat.math.ethz.ch/mailman/listinfo/r-help

Reply via email to