Functions in R with sapply and lapply

The following describes how to use sapply() and lapply() commands to apply functions to return output in the form of vectors and lists respectively:

1. Create Data Frame

x=c(1,2,3,4,5,6,7)

df=data.frame(x)

2. Use sapply to return vectors

sapply(df,mean)
x
4

sapply(df,median)
x
4

sapply(df,sd)
x
2.160247

3. Use lapply to return lists

lapply(df,mean)
$x
[1] 4

lapply(df,median)
$x
[1] 4

lapply(df,sd)
$x
[1] 2.160247

Subscribe to my mailing list, and receive my free e-book; “R: Regression Analysis and Data Structuring Methods”.
Subscribe to my mailing list, and receive my free e-book; “R: Regression Analysis and Data Structuring Methods”. You will also receive regular e-mail updates regarding data science and programming tips and tutorials.
You can unsubscribe at any time, and your details will not be shared with any third party. Your e-mail details will be used for the sole purpose of circulating the e-book along with regular data science newsletters.
Never display this again