[R] subscripts in lists

M.Kondrin mkondrin at hppi.troitsk.ru
Tue Aug 12 02:10:41 CEST 2003

Chris Knight wrote:
> 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

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

More information about the R-help mailing list