Manipulation of list elements
R allows us to add, delete, or update elements in the list. We can update an element of a list from anywhere, but elements can add or delete only at the end of the list. To remove an element from a specified index, we will assign it a null value. We can update the element of a list by overriding it from the new value. Let see an example to understand how we can add, delete, or update the elements in the list.
Example
# Creating a list containing a vector, a matrix and a list. list_data <- list(c("Shubham","Arpita","Nishka"), matrix(c(40,80,60,70,90,80), nrow = 2), list("BCA","MCA","B.tech")) # Giving names to the elements in the list. names(list_data) <- c("Student", "Marks", "Course") # Adding element at the end of the list. list_data[4] <- "Moradabad" print(list_data[4]) # Removing the last element. list_data[4] <- NULL # Printing the 4th Element. print(list_data[4]) # Updating the 3rd Element. list_data[3] <- "Masters of computer applications" print(list_data[3])
Output:
[[1]] [1] "Moradabad" $<NA> NULL $Course [1] "Masters of computer applications"