Site icon Spark By {Examples}

R Combine Two or Multiple Lists

r combine two lists

To append two lists into a single list or combine multiple lists in R, you can use either the combine function c() or append() function. In this article, I will explain examples of using these two methods to combine multiple lists in R.

Let’s create the two lists to use, I will define them as list1 and list2.


# Create two lists
list1 = list('sai','ram','deepika','sahithi')
list2 = list('kumar','scott','Don','Lin')

1. R Combine Two Lists using c()

By using combine function c() you can append two lists into a single list in R. This function takes two lists as an argument and returns the combined list. The following example combines the elements from list1 and list2 objects into a single list list3.

Here c() is a combined function from the base package that can be used to combine lists, vectors, and other objects. These base functions are default available with the R installation and automatically loaded to the program.


# Using c()
list3 <- c(list1,list2)
print(list3)

Yields below output.

r append two lists

2. Combine Two Lists using append()

Alternatively, you can also use append() to get two lists into a single list in R. This function also takes two lists as an argument and returns the combined list.


# Using append()
list3 <- append(list1,list2)
print(list3)

Yields the same output as above.

3. Using rlist Package

Package rlist provides a list.append() function to add multiple lists to the list. In order to use this function first, you need to install R package by using install.packages("rlist") and load it using the library("rlist").


# Using list.append()
library('rlist')
list3 <- list.append(list1,list2)
print(list3)

Yields the same output as above.

4. Combine Multiple Lists using append()

Finally by using list.append() let’s combine multiple lists into a single list in R. The below examples combine elements from list1, list2 and anotherList into a single list list3.


# combine multiple lists
library('rlist')
anotherList <- list('A','B')
list3 <- list.append(list1,list2,anotherList)
print(list3)

5. Complete Example

Following is a complete example of appending two lists.


# Create two lists
list1 = list('sai','ram','deepika','sahithi')
list2 = list('kumar','scott','Don','Lin')

# Using c()
list3 <- c(list1,list2)
print(list3)

# Using append()
list3 <- append(list1,list2)
print(list3)

# Using list.append()
library('rlist')
list3 <- list.append(list1,list2)
print(list3)

6. Conclusion

In this article, you have learned how to append two lists into a single list using the R c() combine function and append() function from R base package. And also leveraged using the append() function from rlist package.

Related Articles

Exit mobile version