Last active
July 19, 2024 15:09
-
-
Save leeper/d6d085ac86d1e006167e to your computer and use it in GitHub Desktop.
One-line push and pop in R
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| # 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/ |
Shouldn't pop reassign the reduced list/vector to object x but return the popped value?
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
This was great! Inspired me to take this, make some mods, and add
shiftandunshift(a la Perl) for left-side operations. Plus, I madepopandshiftreturn the value taken from the queue, andpushandunshiftreturninvisible(). See here: https://gist.github.com/mpettis/b7bfeff282e3b052684fThanks for this!