Skip to content

Instantly share code, notes, and snippets.

@leeper
Last active January 5, 2021 18:51
Show Gist options
  • Star 9 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save leeper/d6d085ac86d1e006167e to your computer and use it in GitHub Desktop.
Save leeper/d6d085ac86d1e006167e to your computer and use it in GitHub Desktop.
One-line push and pop in R
# push
push <- function(x, values) (assign(as.character(substitute(x)), c(x, values), parent.frame()))
# pop
pop <- function(x) (assign(as.character(substitute(x)), x[-length(x)], parent.frame()))
# example
z <- 1:3
push(z, 4)
z
pop(z)
pop(z)
z
push(z, 5)
z
pop(z)
pop(z)
pop(z)
pop(z)
pop(z)
push(z, 1:10)
z
# Other peoples' approaches:
# John Myles White: http://www.johnmyleswhite.com/notebook/2009/12/07/implementing-push-and-pop-in-r/
# arrayhelpers: https://github.com/cran/arrayhelpers/blob/master/R/stack.R
# Barry Rowlingson: https://stat.ethz.ch/pipermail/r-help/2003-February/030301.html
# Gabor Grothendieck: http://grokbase.com/p/r/r-help/0814q1w985/r-suggestion-on-how-to-make-permanent-changes-to-a-single-object-in-a-list
# Jeffrey Ryan: http://www.lemnica.com/esotericR/Introducing-Closures/
@mpettis
Copy link

mpettis commented Feb 10, 2016

This was great! Inspired me to take this, make some mods, and add shift and unshift (a la Perl) for left-side operations. Plus, I made pop and shift return the value taken from the queue, and push and unshift return invisible(). See here: https://gist.github.com/mpettis/b7bfeff282e3b052684f

Thanks for this!

@geotheory
Copy link

Shouldn't pop reassign the reduced list/vector to object x but return the popped value?

@geotheory
Copy link

Been working on this for 3 years. IMO pop should be

pop <- function(x){
  assign(as.character(substitute(x)), x[-length(x)], parent.frame())
  return(x[length(x)])
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment