[R] queue implementation?

Barry Rowlingson b.rowlingson at lancaster.ac.uk
Tue Sep 7 09:56:08 CEST 2010


On Tue, Sep 7, 2010 at 8:11 AM, rajeshj at cse.iitm.ac.in
<rajeshj at cse.iitm.ac.in> wrote:
>
> Hi,
>
> is there a queue implementation in R?

 Tried RSiteSearch("queue")? There's one in the filehash package that
uses on-disk databases, which means it's probably fast and can handle
massive data sets.

 Conversely try this implementation which I hacked up between
breakfast and being late to work. It uses environments to handle the
dreaded "R only has pass-by-value" problem, and is probably okay for
smallish queues. And could be improved in many ways:

queue = function(){
  e=new.env()
  q=list()
  assign("q",q,envir=e)
  class(e)=c("queue","environment")
  e
}

push.queue=function(e,v){
  q=c(v,get("q",envir=e))
  assign("q",q,envir=e)
  v
}

pop.queue=function(e){
  q=get("q",envir=e)
  v=q[[length(q)]]
  if(length(q)==1){
      assign("q",list(),e)
    }else{
      assign("q",q[1:(length(q)-1)],e)
    }
  return(v)
}

print.queue=function(x,...){
  print(get("q",envir=x))
}

 And some usage:

 > q=queue()
 > push.queue(q,34)
 [1] 34
 > push.queue(q,5.44)
 [1] 5.44
 > push.queue(q,"Hello")
 [1] "Hello"
 > pop.queue(q)
 [1] 34
 > pop.queue(q)
 [1] 5.44
 > pop.queue(q)
 [1] "Hello"
 > pop.queue(q)
 Error in q[[length(q)]] : attempt to select less than one element

Barry



More information about the R-help mailing list