w3resource

Select second element of a Given Nested list in R Programming


Write a R program to select second element of a given nested list.

Sample Solution:

R Programming Code :

# Create a nested list with three sublists, each containing two elements
x = list(list(0,2), list(3,4), list(5,6))

# Print a message indicating the following output is the original nested list
print("Original nested list:")

# Print the original nested list
print(x)

# Extract the second element from each sublist using lapply and the '[[', 2 function
e = lapply(x, '[[', 2)

# Print a message indicating the following output is the second element of each sublist
print("Second element of the nested list:")

# Print the extracted second elements from each sublist
print(e)

Output:

[1] "Original nested list:"
[[1]]
[[1]][[1]]
[1] 0

[[1]][[2]]
[1] 2


[[2]]
[[2]][[1]]
[1] 3

[[2]][[2]]
[1] 4


[[3]]
[[3]][[1]]
[1] 5

[[3]][[2]]
[1] 6


[1] "Second element of the nested list:"
[[1]]
[1] 2

[[2]]
[1] 4

[[3]]
[1] 6                         

Explanation:

  • Create Nested List:
    x = list(list(0,2), list(3,4), list(5,6))
    • Creates a nested list x with three sublists. Each sublist contains two numbers.
  • Print Original Nested List:
    print("Original nested list:")
    print(x)
    • Prints the message "Original nested list:" followed by the nested list x.
  • Extract Second Elements:
    e = lapply(x, '[[', 2)
    • Uses lapply to apply the extraction function [[ to each sublist in x, retrieving the second element from each sublist. The results are stored in e.
  • Print Extracted Second Elements:
    print("Second element of the nested list:")
    print(e)
    • Prints the message "Second element of the nested list:" followed by the extracted second elements stored in e.

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 add element at the end of the list.
Next: Write a R program to create a list containing a vector, a matrix and a list and remove the second element.

Test your Programming skills with w3resource's quiz.

What is the difficulty level of this exercise?



Follow us on Facebook and Twitter for latest update.