[R] stack operations on vectors

Thomas Lumley thomas at biostat.washington.edu
Thu Apr 20 20:41:22 CEST 2000


On Thu, 20 Apr 2000, Aidan Dysart wrote:

> It would be nie to have some basic stack operations for simple vectors and
> lists. ie:
> 
> > a <- c(1,2,3,4,5)
> > b <- pop(a)
> > a
> [1] 1 2 3 4
> >b
> [1] 5
> > push(b, 6)
> > b
> [1] 5 6
> 
> notice how pop and push modify the original vector and not local copy
> inside the functions environment. Is there any way to do this? I tried
> this:

There are two ways to do this sort of thing.  One is similar to what you
were doing, but is, I think, considered harmful (messing with frames
should be restricted to places where it is essential).

a <- c(1,2,3,4,5)
pop<-function(x) eval(substitute(x<-x[-1]),parent.frame())
> a
[1] 1 2 3 4 5
> pop(a)
> a
[1] 2 3 4 5



The other is to define a stack class, eg
> makeStack<-function(x){
 pop<-function() if (length(x)>1) x<<-x[-1]
 push<-function(y) x<<-c(y,x)
 value<-function() x
 rval<-list(pop=pop,push=push,value=value)
 class(rval)<-"myStack"
 rval
 }

> print.myStack<-function(x) print(x$value())
> a<-makeStack(1:5)
> a
[1] 1 2 3 4 5
> a$pop()
> a
[1] 2 3 4 5
> a$pop()
> a
[1] 3 4 5
> a$push(3)
> a
[1] 3 3 4 5


	-thomas

Thomas Lumley
Assistant Professor, Biostatistics
University of Washington, Seattle

 

-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-
r-help mailing list -- Read http://www.ci.tuwien.ac.at/~hornik/R/R-FAQ.html
Send "info", "help", or "[un]subscribe"
(in the "body", not the subject !)  To: r-help-request at stat.math.ethz.ch
_._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._



More information about the R-help mailing list