List in R:
In this tutorial we will learn about list in R. Lists provide a way to store a variety of objects of possibly varying modes in a single R object. Note that when forming a list in R, the mode of each object in the list is retained, Which is not possible in vectors.
1 2 | mylist = list ( c (1,4,6), "dog" ,3, "cat" , TRUE , c (9,10,11)) mylist |
output:
[[1]]
[1] 1 4 6
[[2]]
[1] “dog”
[[3]]
[1] 3
[[4]]
[1] “cat”
[[5]]
[1] TRUE
[[6]]
[1] 9 10 11
1 | sapply (mylist,mode) |
[1] “numeric” “character” “numeric” “character” “logical” “numeric”
Merging Lists in R
You can merge many lists into one list by placing all the lists inside one list() function.
1 2 3 4 5 6 7 8 9 | # Create two lists. list1 <- list (1,2,3) list2 <- list ( "Jan" , "Feb" , "Mar" ) # Merge the two lists. merged.list <- c (list1,list2) # Print the merged list. print (merged.list) |
When we execute the above code, it produces the following result –
[[1]]
[1] 1
[[2]]
[1] 2
[[3]]
[1] 3
[[4]]
[1] “Jan”
[[5]]
[1] “Feb”
[[6]]
[1] “Mar”