w3resource

R Programming: Select second element of a given nested list

R Programming: List Exercise-5 with Solution

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

Sample Solution:

R Programming Code :

x = list(list(0,2), list(3,4), list(5,6))
print("Original nested list:")
print(x)
e = lapply(x, '[[', 2)
print("Second element of the nested list:")
print(e)

Sample 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                         

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.