R Lists

R provides list() function to create lists. A list may contain different objects or we can also say that it can combine objects of different types like strings, integers, vectors, matrix. A list is a generic vector. A vector has all elements of the same type, but a list may contain elements of different types.

Creating a list

The following command generates a list that contains students data. In this, there are two vectors, a string and a boolean value.

x <- list(c(1, 3, 5), c('sophiya', 'somya', 'Jorz'), "IT", TRUE)
[[1]]
[1] 1 3 5

[[2]]
[1] "Sophiya" "Somya"   "Jorz"   

[[3]]
[1] "IT"

[[4]]
[1] TRUE

Give name to the list element

We can give a particular name to each of the list elements with the help of the names() function, for example -

x <- list(c(1, 3, 5), c('sophiya', 'somya', 'Jorz'), "IT")
names(x) <- c("id", "name", "Department")
print(x)




Access element of list

A list element can be accessed by its index. It starts with index 1, unlike in other programming languages, the element starts with 0 index. We can use the [ ] brackets for indexing.

print(x[1])
[[1]]
[1] 1 3 5

Add element to an existing list

Suppose, we have the following lists.

x <- list(c(1, 3, 5), c('sophiya', 'somya', 'Jorz'), "IT", TRUE)

We can add a new element to the end of the list either by assigning the new value to the list index (increase one to the last index) or by giving a name to the new index. The below list contains student's data. We add a new list element of name gender.

x <- list(c(1, 3, 5), c('sophiya', 'somya', 'Jorz'), "IT", TRUE)
x$gender <- c('F', 'F', 'M')
print(x)
[[1]]
[1] 1 3 5

[[2]]
[1] "Sophiya" "Somya"   "Jorz"   

[[3]]
[1] "IT"

[[4]]
[1] TRUE

$gender
[1] "F" "F" "M"

We can also add an element to the list by using the index. like -

x[6] <- c(F, F, M)
x




Get length of a list

In R, the length() function returns the length of a list.

length(x)
[1] 5

Delete list element

To delete a list element, simply assign it to a null value.

x[5] <- NULL
x
[[1]]
[1] 1 3 5

[[2]]
[1] "Sophiya" "Somya"   "Jorz"   

[[3]]
[1] "IT"

[[4]]
[1] TRUE

Update list element

To modify a list element, simply assign the element index with new value with the help of assignment operator. In the given example, we modify the third list element.

x <- list(c(1, 3, 5), c('sophiya', 'somya', 'Jorz'), "IT", TRUE)
x[3] <- "Mech"
print(x)






Read more articles


General Knowledge



Learn Popular Language