Open In App

How to create a list in R

Last Updated : 03 Apr, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

In this article, we will discuss What is a list and various methods to create a list using R Programming Language.

What is a list?

A list is the one-dimensional heterogeneous data i.e., which stores the data of various types such as integers, float, strings, logical values, and characters. These lists provide flexibility and can be accessed by using indexing. Some of the methods to create the list are:

Creating a list by using the ‘list()’ function

This method is used to create the list by using the function ‘list()’ efficiently. In the below example, we created the list by using the function ‘list()’.

R
# creating list
list1 = list("apple", "A", 550, FALSE, 5.1, c(1, 2, 3,4,5))
print("The list is")
print(list1)

Output:

[1] "The list is"
[[1]]
[1] "apple"

[[2]]
[1] "A"

[[3]]
[1] 550

[[4]]
[1] FALSE

[[5]]
[1] 5.1

[[6]]
[1] 1 2 3 4 5

In the below example, we created the list by using the function ‘list()’.

R
# creating list
list=  list("gfg", 550 , TRUE, 15.5, "G")
print("The list is")
print(list)

Output:

[1] "The list is"
[[1]]
[1] "gfg"

[[2]]
[1] 550

[[3]]
[1] TRUE

[[4]]
[1] 15.5

[[5]]
[1] "G"

Creating list by using Concatenation

This method is used to create the list by using the function ‘c()’ efficiently. In the below example, we created the the vectors and by using it, we created the list by using the function ‘c()’.

R
vec1 = c("gfg", "a", "h")                 
vec2 = c("ramu", "b", "rakesh")            
vec3 = c("lokesh", "suresh")               

#creating list
list = c(vec1, vec2, vec3)
print("The list is")
print(list)

Output:

[1] "The list is"
[1] "gfg" "a" "h" "ramu" "b" "rakesh" "lokesh" "suresh"

In the below example, we created the the vectors and by using it, we created the list by using the function ‘c()’.

R
a = c(43, 5.6, 23, 76)                 
b = c(550, 750.5, 25, 1.5)              

#creating list
list1 = c(a,b)
print("The list is")
print(list1)

Output:

[1] "The list is"
[1] 43.0 5.6 23.0 76.0 550.0 750.5 25.0 1.5

Conclusion

In conclusion, we learned about how to create a list by using R. R language offers versatile tools while creating the list efficiently.


Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads