A useful function of lapply is to let you apply a different function to one or more than one groups of data.
For example, we can apply the "mean" function to the data that we want to calculate the average of.
1. Let's calculate the average of just one group of data.(the average of the score column)
Here is a WRONG way to do so.
moody <- read.csv("https://raw.githubusercontent.com/kunal0895/RDatasets/master/Moody2018.csv")
average_score <- lapply(moody$SCORE,mean)
average_score
We got nothing because lapply considers each value in the SCORE as a list of numbers with length 1, so we got the same number as before.
So we need to first group all the data in SCORE into one group.
moody <- read.csv("https://raw.githubusercontent.com/kunal0895/RDatasets/master/Moody2018.csv")
value <- list(moody$SCORE)
# so in this case we consider the data in SCORE as a whole list of data
average_score <- lapply(value,mean)
average_score
2. Now let's calculate the average of more than one group of data.
For example, let's calculate the average of "SCORE" and "FINALEXAM" columns.
moody <- read.csv("https://raw.githubusercontent.com/kunal0895/RDatasets/master/Moody2018.csv")
value <- list(moody$SCORE,moody$FINALEXAM)
#You can add as many vectors as you like.
average <- lapply (value, mean)
average