Ian Gow
Ian Gow

Reputation: 3535

How to append a vector to a list of vectors in R?

This question is related to an earlier one, except the answer there (use c() function) is precisely what was not working for me.

First I create a list of vectors and then an additional vector.

a_list <- lapply(mtcars, as.integer)
junk <- c(1:length(a_list[[1]]))

Now, if use c(a_list, junk) (as suggested in the answer to the earlier question), I get a completely different answer from what I get if I say a_list[["junk"]] <- junk (the latter yielding the desired result). It seems that what gets added by the former approach is as.list(junk).

How can I add junk using c() without it being converted to the result of as.list(junk)?

Upvotes: 4

Views: 10296

Answers (1)

Ian Gow
Ian Gow

Reputation: 3535

Use list() in this way: c(a_list, junk=list(junk)).

In trying to work out exactly what was being added in the problematic scenario above (to better formulate my question), I realized that list and as.list do very different things. By turning junk into a single-element list (using list()), it gets added "as is" in the desired fashion.

Actually this was buried in a "show more comments" comment to Dirk Eddelbuettel's answer and (more embarrassingly) in the help for c() itself. Quoting the help:

## do *not* use
c(ll, d = 1:3) # which is == c(ll, as.list(c(d = 1:3))
## but rather
c(ll, d = list(1:3))  # c() combining two lists

Upvotes: 2

Related Questions