stackUtilities | R Documentation |
You can "pop" data off the end of a vector, one element at a time, with
pop()
. You can also "push" new data onto the end of the vector with
push()
. The analogous functions for working at the start of a
vector are shift()
and unshift()
: shift()
removes the
first element of your vector, and unshift()
prepends new elements to
your vector.
push(x, values) pop(x) unshift(x, values) shift(x)
x |
Object, typically a vector or a list. |
values |
Object to be added to |
An important and unusual feature of push(), pop(), shift(),
and
unshift()
is that they modify objects "in place"—that is, even
when no explicit assignment is done. For example, pop(x)
will return
the last value of x
, but it will also remove the last value from the
x
object. The examples illustrate this point.
These functions are adapted from Matt Pettis's code at https://gist.github.com/mpettis/b7bfeff282e3b052684f.
Previous versions of these functions were adapted from Jeffrey A. Ryan's
code at http://www.lemnica.com/esotericR/Introducing-Closures/. That
code works but is based on the creation of "stack" objects that contain
their own environments. One consequence is that changing a copy of a stack
object changes the original stack object, and vice versa. Note too that,
in Ryan's code, the traditional meanings of shift()
and
unshift()
are reversed: he uses shift()
to concatenate
objects, unshift()
to remove a value from an object.
pop()
and shift()
will return a scalar, that is, an object of
length\NB1. push()
and unshift()
don't return anything.
Matt Pettis
John G. Bullock
Thomas Leeper's Gist
describes his own implementation of pop()
and push()
and
includes links to six other implementations. Some of these implementations
of pop()
and push()
do not have the modify-in-place
characteristic of the corresponding Perl functions. This quality is also
absent from the constructor function at https://stackoverflow.com/a/14489296/697473.
myStack <- 1:3 push(myStack, 4) myStack # [1] 1 2 3 4 pop(myStack) # [1] 4 shift(myStack) # [1] 1 myStack # [1] 2 3 unshift(myStack, "hello") myStack # [1] "hello" "2" "3" myList <- list(1, 2, 3) # list with three elements push(myList, 4) myList # list with 4 elements shift(myList) # returns 1 myList[[1]] # first element of myList is now 2
Add the following code to your website.
For more information on customizing the embed code, read Embedding Snippets.