Append an object to a list in R in amortized constant time, O(1)?

If I have some R list mylist, you can append an item obj to it like so:

mylist[[length(mylist)+1]] <- obj

But surely there is some more compact way. When I was new at R, I tried writing lappend() like so:

lappend <- function(lst, obj) {
    lst[[length(lst)+1]] <- obj
    return(lst)
}

but of course that doesn’t work due to R’s call-by-name semantics (lst is effectively copied upon call, so changes to lst are not visible outside the scope of lappend(). I know you can do environment hacking in an R function to reach outside the scope of your function and mutate the calling environment, but that seems like a large hammer to write a simple append function.

Can anyone suggest a more beautiful way of doing this? Bonus points if it works for both vectors and lists.

17 Answers
17

Leave a Comment