w3resource

R Programming: Create a List and remove the second element

R Programming: List Exercise-6 with Solution

Write a R program to create a list containing a vector, a matrix and a list and remove the second 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", "PHP", "Java"))

# Print the original list
print("List:")
print(list_data)

# Print a message indicating that the second element will be removed
print("Remove the second element of the list:")

# Remove the second element from the list
list_data[2] = NULL

# Print the modified 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"

[[3]][[2]]
[1] "PHP"

[[3]][[3]]
[1] "Java"


[1] "Remove the second element of the list:"
[1] "New list:"
[[1]]
[1] "Red"   "Green" "Black"

[[2]]
[[2]][[1]]
[1] "Python"

[[2]][[2]]
[1] "PHP"

[[2]][[3]]
[1] "Java"                         

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 containing:
        • A vector with elements "Red", "Green", and "Black".
        • A matrix with values 1, 3, 5, 7, 9, 11 arranged into 2 rows.
        • A nested list containing "Python", "PHP", and "Java".
  • Print Original List:
    • print("List:")
      • Prints the label "List:".
    • print(list_data)
      • Prints the contents of list_data, which shows the vector, matrix, and nested list.
  • Print Message about Removal:
    • print("Remove the second element of the list:")
      • Prints the message indicating that the second element of the list will be removed.
  • Remove Second Element:
    • list_data[2] = NULL
      • Removes the second element (the matrix) from the list by setting it to NULL.
  • Print Modified List:
    • print("New list:")
      • Prints the label "New list:".
    • print(list_data)
      • Prints the modified list_data, which now contains only the vector and the nested list/

R Programming Code Editor:



Have another way to solve this solution? Contribute your code (and comments) through Disqus.

Previous: Write a R program to select second element of a given nested list.
Next: Write a R program to create a list containing a vector, a matrix and a list and update the last element.

Test your Programming skills with w3resource's quiz.

What is the difficulty level of this exercise?



Become a Patron!

Follow us on Facebook and Twitter for latest update.

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-6.php