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
– 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
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 A 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.
A = list(list(1,3), list(2,5), list(6,7))
print("Original nested list is:")
## [1] "Original nested list is:"
print(A)
## [[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
elem = lapply(A, '[[', 2)
print("Second element of the nested list is:")
## [1] "Second element of the nested list is:"
print(elem)
## [[1]]
## [1] 3
##
## [[2]]
## [1] 5
##
## [[3]]
## [1] 7