R Program to select second element of a given nested list

How to select the second element of a given nested list

Here we explain how to write an R program to select the second element of a given nested list. Here we are using a built-in function lapply() for this. This function helps to returns a list of the same length as the given list. The result of applying FUN to the corresponding  X elements are each element of the returned list. The syntax of this function is 

lapply(X, FUN, …) 

Where X is an X a vector (atomic or list) or an expression object and FUN is the function to be applied to each element of X

How to select the second element of a given nested list in the R program

Below are the steps used in the R program to select the second element of a given nested list. In this R program, we directly give the values to a built-in function lapply(). Here we are using variable for holding the nested list. And variable elem is the result list after applying the function to each element of A. Call the function lapply() for applying the function to list elements.

ALGORITHM

STEP 1: Assign variable with a nested list

STEP 2: Print the original nested list

STEP 3: Call the function apply() as lapply(A, '[[', 2) for finding the second element of each lists

STEP 4: Assign result list into the variable elem

STEP 4: Print the result 

R Source Code

                                          A = list(list(1,3), list(2,5), list(6,7))
print("Original nested list is:")
print(A)
elem = lapply(A, '[[', 2)
print("Second element of the nested list is:")
print(elem)
                                      

OUTPUT

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

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


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

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


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

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


[1] "Second element of the nested list is:"
[[1]]
[1] 3

[[2]]
[1] 5

[[3]]
[1] 7