[R] shift and pop equivalent in R

Barry Rowlingson b.rowlingson at lancaster.ac.uk
Tue Apr 20 20:50:29 CEST 2010


On Tue, Apr 20, 2010 at 7:03 PM, Xie Chao <xiechaos at gmail.com> wrote:
> Dear All,
>
> I am wondering is there any shift (or pop or push or unshift) equivalent in R?
> For example,
> shift(x)   # should return x[1], and x becomes x[-1]
>

 I seem to have implemented a FIFO stack in 2003:

http://finzi.psych.upenn.edu/R/Rhelp02/archive/15541.html

 but note the reply commenting on the existence of the "stack"
function in R which stacks data on top of other data.

Here's sample usage once you've loaded the code from that old posting:

> s=stack()
> push(s,1)
> s
[[1]]
[1] 1

> push(s,3)
> push(s,4)
> pop(s)
[1] 4
> pop(s)
[1] 3
> s
[[1]]
[1] 1

 If you want to implement a 'shift' method, just look at the existing
pop and push methods and write something similar. Note how the
functions are created on the object, and then called from S3 methods.
Note the use of <<- within the functions on the object. There's
probably better ways to do this, and with S4 methods.

Barry



-- 
blog: http://geospaced.blogspot.com/
web: http://www.maths.lancs.ac.uk/~rowlings
web: http://www.rowlingson.com/
twitter: http://twitter.com/geospacedman
pics: http://www.flickr.com/photos/spacedman



More information about the R-help mailing list