Skip to content
Prev 7966 / 398503 Next

.Last.value or % or ANS or ... (was unix)

Bill Simpson <wsi at gcal.ac.uk> writes:
Why not implement a LIFO stack? Here is a first attempt:

        #
        # Flush the stack 
        # (call this to create the stack)
        #
        flush <- function()
         {
         stack <<- list()
         }
 
        #
        # Push a value onto the stack
        #
        push <- function()
         {
         stack <<- c(stack, .Last.value)
         }

        #
        # Pull a value from the stack 
        # (default is last pushed value)
        #
        pull <- function(x = 0)
         {
         stack[[length(stack) - x]]
         }

        #
        # Pull a value from the stack and remove it
        # (default is last pushed value)
        #
        pop <- function(x = 0) 
         {
         pop <- stack[[length(stack) - x]]
         stack <<- stack[-length(stack) + x]
         pop
         }

You still need to push() the values you want to keep onto the stack.
Another limitations of the above code is that objects are stored as
'atoms':

        > flush()
        > a <- c(1,2,3,4,5)
        > mean(a)
        [1] 3
        > push()
        > stack
        [[1]]
        [1] 3

        > a
        [1] 1 2 3 4 5
        > push()
        > stack
        [[1]]
        [1] 3

        [[2]]
        [1] 1

        [[3]]
        [1] 2

        [[4]]
        [1] 3

        [[5]]
        [1] 4

        [[6]]
        [1] 5

        > pull(1)
        [1] 4
        > pop(1)
        [1] 4
        > stack
        [[1]]
        [1] 3

        [[2]]
        [1] 1

        [[3]]
        [1] 2 

        [[4]]
        [1] 3

        [[5]]
        [1] 5

Which makes it pretty useless for vector and matrix results but there
should be a way round that.

Mark


--
Mark Myatt


-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-
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
_._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._