[R] subscripts in lists

Peter Wolf s-plus at wiwi.uni-bielefeld.de
Tue Aug 12 08:57:12 CEST 2003


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 <christopher.knight at plant-sciences.oxford.ac.uk> 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
pwolf at wiwi.uni-bielefeld.de




More information about the R-help mailing list