Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

A better way to push and pop to/from lists in R?

Tags:

r

If foo <- list(), I find myself writing foo[[length(foo)+1]] <- bar a lot when really I just want to write push(foo, bar).

Similarly (though much less frequently) bar <- foo[[length(foo)]] would be much nicer as bar <- pop(foo).

  1. Is there a better way to do this in base R?
  2. Failing that, has anyone written a package that makes these basic list operations less syntactically torturous?

It's the repetition of the variable name that kills me. Consider:

anInformative.selfDocumenting.listName[[length(anInformative.selfDocumenting.listName)+1]] <- bar

edit:

foo <- append(foo, bar) doesn't work for me

foo <- list()
for (i in 1:10) {
  x <- data.frame(a=i, b=rnorm(1,0,1))
  foo[[length(foo)+1]] <- x
}
str(foo)

Gives a list of 10 objects as expected.

foo <- list()
for (i in 1:10) {
  x <- data.frame(a=i, b=rnorm(1,0,1))
  foo <- append(foo, x)
}
str(foo)

Gives a list of 20 objects.

like image 579
logworthy Avatar asked Feb 24 '15 03:02

logworthy


1 Answers

foo[[length(foo)+1]] <- bar

could be rewritten as

foo <- append(foo, bar)

and

bar <- foo[[length(foo)]]

could be rewritten as

bar <- tail(foo,1)

Note that with functional languages such as R functions generally aren't supposed to changes values of parameters passed to them; typically you return a new object which you can assign elsewhere. The function should have no "side effects." Functions like push/pop in other languages usually modify one of the passed parameters.

like image 59
MrFlick Avatar answered Oct 01 '22 18:10

MrFlick