in fact there is a subtelty with the c()
function. If you do:
x <- list()
x <- c(x,2)
x = c(x,"foo")
you will obtain as expected:
[[1]]
[1]
[[2]]
[1] "foo"
but if you add a matrix with x <- c(x, matrix(5,2,2)
, your list will have another 4 elements of value 5
!
You would better do:
x <- c(x, list(matrix(5,2,2))
It works for any other object and you will obtain as expected:
[[1]]
[1]
[[2]]
[1] "foo"
[[3]]
[,1] [,2]
[1,] 5 5
[2,] 5 5
Finally, your function becomes:
push <- function(l, ...) c(l, list(...))
and it works for any type of object. You can be smarter and do:
push_back <- function(l, ...) c(l, list(...))
push_front <- function(l, ...) c(list(...), l)