Skip to content

Instantly share code, notes, and snippets.

@Dulani
Forked from leeper/pushpop.R
Created April 4, 2019 13:34
Show Gist options
  • Save Dulani/fd38fc0bcb7ea5565720852ef449ee88 to your computer and use it in GitHub Desktop.
Save Dulani/fd38fc0bcb7ea5565720852ef449ee88 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/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment