lapply

lapply(X, a function, ...)
x is the data that you want to deal with, return a list of the same length as x, each element of which is the result of applying the function to the corresponding element of x

Example

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