Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to combine two lists in R

Tags:

list

r

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).

like image 809
Rohit Singh Avatar asked Oct 03 '22 10:10

Rohit Singh


People also ask

How do I put two lists together in R?

combine. lists(list1, list2) returns a list consisting in the elements found in either list1 or list2, giving precedence to values found in list2 for dimensions found in both lists. Two lists to be combined.

How do I merge a list of lists in R?

Combine lists in R Two or more R lists can be joined together. For that purpose, you can use the append , the c or the do. call functions. When combining the lists this way, the second list elements will be appended at the end of the first list.

How do I make a list in R list?

How to Create Lists in R? We can use the list() function to create a list. Another way to create a list is to use the c() function. The c() function coerces elements into the same type, so, if there is a list amongst the elements, then all elements are turned into components of a list.


1 Answers

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))
like image 206
Vincent Bonhomme Avatar answered Oct 06 '22 13:10

Vincent Bonhomme