[R] subscripts in lists
Richard A. O'Keefe
ok at cs.otago.ac.nz
Tue Aug 12 00:24:41 CEST 2003
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.
More information about the R-help
mailing list