Skip to content

Instantly share code, notes, and snippets.

@mpettis
Last active March 18, 2022 09:24
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mpettis/b7bfeff282e3b052684f to your computer and use it in GitHub Desktop.
Save mpettis/b7bfeff282e3b052684f to your computer and use it in GitHub Desktop.
R: Push, Pop, Shift, Unshift
# Inspired:
# https://gist.github.com/leeper/d6d085ac86d1e006167e
# http://www.johnmyleswhite.com/notebook/2009/12/07/implementing-push-and-pop-in-r/
push <- function(x, values) {
assign(as.character(substitute(x)), c(x, values), parent.frame())
invisible()}
pop <- function(x) {
if(length(x) == 0) {return(NA)}
popret <- x[length(x)]
assign(as.character(substitute(x)), x[-length(x)], parent.frame())
return(popret)}
unshift <- function(x, values) {
assign(as.character(substitute(x)), c(values, x), parent.frame())
invisible()}
shift <- function(x) {
if(length(x) == 0) {return(NA)}
shiftret <- x[1]
assign(as.character(substitute(x)), x[2:(length(x))], parent.frame())
return(shiftret)}
# z <- letters[1:11]
# z
#
# pop(z)
# z
# push(z, "v")
# z
# shift(z)
# z
# unshift(z, c("m", "n"))
# z
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment