Dear Priyam,

Hope you are doing great.

lapply(): It is used when we wish to apply a given function to every element of a list and obtain a list as result.
>It can be used for other objects like dataframes, lists or vectors. 
>The output returned is a list (thus the l in the function name) which has the same number of elements as the object passed to it.

Lets take one example to see the working of lapply().
#create a list of matrices:
A<-matrix(1:9, 3,3)
B<-matrix(4:15, 4,3)
C<-matrix(8:10, 3,2)
MyList<-list(A,B,C) # display the list
# extract the second column from the list of matrices, using the selection operator "["
lapply(MyList,"[", , 2)
## [[1]]
## [1] 4 5 6
##
## [[2]]
## [1] 8 9 10 11
##
## [[3]]
## [1] 8 9 10
# Another example: we now extract the first row from the list of matrices, using the selection operator "["
lapply(MyList,"[", 1, )
## [[1]]
## [1] 1 4 7
##
## [[2]]
## [1] 4 8 12
##
## [[3]]
## [1] 8 8
The [ notation is the select operator. Recall for example, that to extract all the elements of the third line of B requires: {r}B[3,] (the nothing after the comma means “any”)
The [[ ]] notation expresses the fact that the we are dealing with lists: [[2]] means the second element of the list. This is shown also in the output given by R
The output is a list with as many elements as the element in the input
Note that we could also have extracted a single element for each matrice, like this:
lapply(MyList,"[", 1, 2)
## [[1]]
## [1] 4
##
## [[2]]
## [1] 8
##
## [[3]]
## [1] 8

sapply():sapply works as lapply, but it tries to simplify the output to the most elementary data structure that is possible. In effect, as can be seen in the base manual, sapply is a ‘wrapper’ function for lapply.

lets understand sapply() through one example.

lapply(MyList,"[", 2,1 )
## [[1]]
## [1] 2
##
## [[2]]
## [1] 5
##
## [[3]]
## [1] 9
but sapply returns a vector instead.
 
sapply(MyList,"[", 2,1 )
## [1] 2 5 9

unless we tell simplify=FALSE as parameter to sapply, in which case a list will be returned:
 
sapply(MyList,"[", 2,1, simplify=F)
## [[1]]
## [1] 2
##
## [[2]]
## [1] 5
##
## [[3]]
## [1] 9

Please go through the above content if you encounter any doubt please do ask.

Please inspire us by sharing your feedback, please click on any one of the smileys for sharing the feedback.

We are ridiculously committed to you and your progress. 

Regards,
Shubham Kumar at Edureka
edureka! Solution Team