Implementing Push and Pop in R

[This article was first published on John Myles White: Die Sudelbücher » Statistics, and kindly contributed to R-bloggers]. (You can report issue about the content on this page here)
Want to share your content on R-bloggers? click here if you have a blog, or here if you don't.

Having grown up with Perl, there are two functions that I desperately miss while programming in R: push and pop. Continually writing

1
vector <- c(vector, new.entry)

tries my patience, while writing

1
2
vector <- rep(NA, inscrutable.constant)
vector[inscrutable.index] <- new.entry

makes me feel like I’m programming in C, rather than a higher-level programming language. That said, here’s a simplistic hack to provide something like an implementation of push and pop in R:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
push <- function(vector.name, item)
{
  eval.parent(parse(text = paste(vector.name, ' <- c(', vector.name, ', ', item, ')',
                                 sep = '')),
              n = 1)
}
 
pop <- function(vector.name)
{
  eval.parent(parse(text = paste(vector.name, ' <- ', 
                                 vector.name, '[-length(', vector.name, ')]',
                                 sep = '')),
              n = 1)
}

Both of these functions are more than a little ugly, because you have to pass in a string that names the vector you want to change, rather than providing its name as a bareword. Even worse, this version of pop doesn’t let you get the value of the item you pop off of the stack, because I’m not sure how to introduce a temporary variable into the parent’s environment without occasionally clobbering the value of an existing variable. If I knew more about scoping and lazy evaluation in R, I think I could implement these two functions as pseudo-macros and solve both concerns. If you know how to do this, please do let me know.

To leave a comment for the author, please follow the link and comment on their blog: John Myles White: Die Sudelbücher » Statistics.

R-bloggers.com offers daily e-mail updates about R news and tutorials about learning R and many other topics. Click here if you're looking to post or find an R/data-science job.
Want to share your content on R-bloggers? click here if you have a blog, or here if you don't.

Never miss an update!
Subscribe to R-bloggers to receive
e-mails with the latest R posts.
(You will not see this message again.)

Click here to close (This popup will not appear again)