R Program to select second element of a given nested list


February 26, 2023, Learn eTutorial
1895

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

For accessing the elements of a list using the R program. we are using a built-in function lapply() for this. Usually, in programming languages, we use loops. There are different types of apply() functions are available to work on lists, vectors, and data frames, also they can be viewed as substitutes to the loop constructs. lapply() is one of them and ' l ' stands for list. This function helps to perform some operations on list objects and return a list of the same length as the list object given as an argument. The return list will be the result of applying FUN to the corresponding elements of X . The syntax of this function is 

lapply(X, FUN, …) 

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

How to access an nth position element in a nested list using R program?

In this R program, we directly give the values to a built-in function lapply(). Here we are using the variable values_lst for holding the nested list. And variable rslt_lst is the result list after applying the function to each element of values_lst. Call the function lapply() for applying the function FUN to list elements, FUN we used is a double square ' [[ ' which will extract one element from a list, here we are selecting the second element of each nested list.

ALGORITHM

STEP 1: Assign variable values_lst with a nested list

STEP 2: Display the original values of the list

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

STEP 4: Assign the result list into the variable rslt_lst

STEP 4: Print the result 

R Source Code

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

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