R Programming: Create and Modify lists with Vectors and Matrices
Write a R program to create a list containing a vector, a matrix and a list and add element at the end of the list.
Sample Solution:
R Programming Code :
# Create a list containing a vector, a matrix, and another list
list_data <- list(c("Red","Green","Black"), matrix(c(1,3,5,7,9,11), nrow = 2),
list("Python", "PHP", "Java"))
# Print the original list
print("List:")
print(list_data)
# Add a new element at the end of the list
print("Add a new element at the end of the list:")
list_data[4] = "New element"
# Print the updated list with the new element
print("New list:")
print(list_data)
Output:
[1] "List:"
[[1]]
[1] "Red" "Green" "Black"
[[2]]
[,1] [,2] [,3]
[1,] 1 5 9
[2,] 3 7 11
[[3]]
[[3]][[1]]
[1] "Python"
[[3]][[2]]
[1] "PHP"
[[3]][[3]]
[1] "Java"
[1] "Add a new element at the end of the list:"
[1] "New list:"
[[1]]
[1] "Red" "Green" "Black"
[[2]]
[,1] [,2] [,3]
[1,] 1 5 9
[2,] 3 7 11
[[3]]
[[3]][[1]]
[1] "Python"
[[3]][[2]]
[1] "PHP"
[[3]][[3]]
[1] "Java"
[[4]]
[1] "New element"
Explanation:
- Create a List:
- list_data <- list(c("Red","Green","Black"), matrix(c(1,3,5,7,9,11), nrow = 2), list("Python", "PHP", "Java"))
- Creates a list named list_data with three elements:
- A vector of colors: "Red", "Green", "Black".
- A matrix with numbers arranged in 2 rows and 3 columns.
- A list of programming languages: "Python", "PHP", "Java".
- Print Original List:
- print("List:")
- print(list_data)
- Displays the original list contents.
- Add New Element to the List:
- print("Add a new element at the end of the list:")
- list_data[4] = "New element"
- Adds a new element "New element" to the end of the list_data.
- Print Updated List:
- print("New list:")
- print(list_data)
- Displays the updated list including the newly added element.
Go to:
PREV : Write a R program to create a list containing a vector, a matrix and a list and give names to the elements in the list. Access the first and second element of the list.
NEXT : Write a R program to select second element of a given nested list.
R Programming Code Editor:
Have another way to solve this solution? Contribute your code (and comments) through Disqus.
Test your Programming skills with w3resource's quiz.
What is the difficulty level of this exercise?
