[R] subscripts in lists
Chris Knight
christopher.knight at plant-sciences.oxford.ac.uk
Mon Aug 11 14:21:53 CEST 2003
I am tying myself in knots over subscripts when applied to lists
I have a list along the lines of:
lis<-list(c("a","b","next","want1","c"),c("d", "next", "want2", "a"))
>From which I want to extract the values following "next" in each
member of the list, i.e. something along the lines of answer<-c(
"want1", "want2"). Is this possible without using loops? The elements
of lis are of different lengths and "next" occurs once per element
somewhere in the middle.
The thought process behind this is:
It's easy enough to do it for an individual element of the list:
lis[[1]][match("next",lis[[1]])+1]
but how to do that to all elements of the list? I can get their
indices e.g. as a list using lapply:
lapply(lapply(lis,match,x="next"),"+",y=1)
or return a particular subscript using:
lapply(lis,"[", i=3)
but don't see how one could combine the two to get answer<-c("want1",
"want2") without resorting to:
answer<-character
for(s in 1:length(lis)){
answer<-c(answer,lis[[s]][match("next",lis[[s]])+1])
}
Am I missing something obvious (or non-obvious)? I suppose the
secondary question is 'should I care?'. I am intending to use this on
hundreds of lists sometimes with tens of thousands of elements, with
more than one version of "next" in each, so felt that the lower
efficiency of looping was likely to matter.
Any help much appreciated,
Chris
--
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Dr. Christopher G. Knight Tel:+44 (0)1865 275 111
Department of Plant Sciences +44 (0)1865 275 790
South Parks Road
Oxford OX1 3RB
UK `
· . , ,><(((º>
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
More information about the R-help
mailing list