Append an object to a list in R?

Posted by Nick on Stack Overflow See other posts from Stack Overflow or by Nick
Published on 2010-03-13T00:14:09Z Indexed on 2010/03/13 0:17 UTC
Read the original article Hit count: 637

Filed under:
|

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 append() like so:

append <- function(lst, obj) {
    lst[[length(list)+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 append(). 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.

© Stack Overflow or respective owner

Related posts about r

    Related posts about beginner