169

I have two lists:

l1 = list(2, 3)
l2 = list(4)

I want a third list:

list(2, 3, 4).

How can I do it in simple way. Although I can do it in for loop, but I am expecting a one liner answer, or maybe an in-built method.

Actually, I have a list:
list(list(2, 3), list(2, 4), list(3, 5), list(3, 7), list(5, 6), list(5, 7), list(6, 7)).
After computing on list(2, 3) and list(2, 4), I want list(2, 3, 4).

Rohit Singh
  • 2,143
  • 3
  • 13
  • 16

3 Answers3

215

c can be used on lists (and not only on vectors):

# you have
l1 = list(2, 3)
l2 = list(4)

# you want
list(2, 3, 4)
[[1]]
[1] 2

[[2]]
[1] 3

[[3]]
[1] 4

# you can do
c(l1, l2)
[[1]]
[1] 2

[[2]]
[1] 3

[[3]]
[1] 4

If you have a list of lists, you can do it (perhaps) more comfortably with do.call, eg:

do.call(c, list(l1, l2))
Scarabee
  • 5,437
  • 5
  • 29
  • 55
Vincent Bonhomme
  • 7,235
  • 2
  • 27
  • 38
  • How could this code be applied to n lists? Let's say I have 100 lists and want to combine them using c(). Could I do this without writing ```c(l1, l2, l3, l4...l100```? – NorthLattitude Jun 22 '21 at 00:02
  • @NorthLattitude when creating lists, there must be a way to put all lists within a list ;-). Otherwise, that's still feasible with `parse/eval`, ie: ```l1 <- "a"; l2 <- "b" ; l3 <- "c"; eval(parse(text=paste0("list(", paste0("l", 1:3, collapse = ", "), ")")))``` – Vincent Bonhomme Sep 14 '21 at 10:45
77

We can use append

append(l1, l2)

It also has arguments to insert element at a particular location.

akrun
  • 874,273
  • 37
  • 540
  • 662
  • @Zach `paste` and `paste0` are to join strings together to a bigger string. Can you describe the problem a bit more as I didn't understand it clearly? – akrun Apr 18 '16 at 02:15
  • 3
    @akrun How is the syntax for more than two lists? – Frosi May 30 '17 at 17:15
  • 8
    @Frosi you can do `c(l1, l2, l3)`, `append()` is just a wrapper for `c()` but only takes two arguments. – s_baldur Jan 16 '19 at 11:13
-2

I was looking to do the same thing, but to preserve the list as a just an array of strings so I wrote a new code, which from what I've been reading may not be the most efficient but worked for what i needed to do:

combineListsAsOne <-function(list1, list2){
  n <- c()
  for(x in list1){
    n<-c(n, x)
  }
  for(y in list2){
    n<-c(n, y)
  }
  return(n)
}

It just creates a new list and adds items from two supplied lists to create one.

John Proestakes
  • 317
  • 2
  • 5