Skip to content

Instantly share code, notes, and snippets.

@leeper
Last active July 19, 2024 15:09
Show Gist options
  • Select an option

  • Save leeper/d6d085ac86d1e006167e to your computer and use it in GitHub Desktop.

Select an option

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
Copy Markdown

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
Copy Markdown

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

@geotheory
Copy link
Copy Markdown

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