R Programming: Update last element in a List with solution
R Programming: List Exercise-7 with Solution
Write a R program to create a list containing a vector, a matrix and a list and update the last element.
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"))
# Print the current state of the list
print("List:")
print(list_data)
# Print a message indicating the next operation
print("Update the third element of the list:")
# Update the third element of the list with a new value
list_data[3] = "R programming"
# Print the updated state of the list
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" [1] "Update the second element of the list:" [1] "New list:" [[1]] [1] "Red" "Green" "Black" [[2]] [,1] [,2] [,3] [1,] 1 5 9 [2,] 3 7 11 [[3]] [1] "R programming"
Explanation:
- Create a List:
- list_data <- list(c("Red","Green","Black"), matrix(c(1,3,5,7,9,11), nrow = 2), list("Python"))
- Constructs a list named list_data with three elements:
- A vector of strings: "Red", "Green", "Black".
- A matrix with the numbers 1, 3, 5, 7, 9, 11 arranged in 2 rows.
- A list containing a single string: "Python".
- Print the List:
- print("List:")
- Outputs the label "List:".
- print(list_data)
- Displays the contents of list_data.
- Update the Third Element:
- print("Update the third element of the list:")
- Outputs the label "Update the third element of the list:".
- list_data[3] = "R programming"
- Replaces the third element of list_data (the list containing "Python") with a new string "R programming".
- Print the Updated List:
- print("New list:")
- Outputs the label "New list:".
- print(list_data)
- Displays the updated list_data, showing the new third element.
R Programming Code Editor:
Have another way to solve this solution? Contribute your code (and comments) through Disqus.
Previous: Write a R program to create a list containing a vector, a matrix and a list and remove the second element.
Next: Write a R program to merge two given lists into one list.
Test your Programming skills with w3resource's quiz.
What is the difficulty level of this exercise?
It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.
https://w3resource.com/r-programming-exercises/list/r-programming-list-exercise-7.php
- Weekly Trends and Language Statistics
- Weekly Trends and Language Statistics