# Applying multiple functions to data frame

**R snippets**, and kindly contributed to R-bloggers]. (You can report issue about the content on this page here)

Want to share your content on R-bloggers? click here if you have a blog, or here if you don't.

A very typical task in data analysis is calculation of summary statistics for each variable in data frame. Standard lapply or sapply functions work very nice for this but operate only on single function. The problem is that I often want to calculate *several* diffrent statistics of the data. For example assume that we want to calculate minimum, maximum and mean value of each variable in data frame.

The simplest solution for this is to write a function that does all the calculations and returns a vector. The sample code is:

**<-**

**function**

**(**x

**)**

**{**

**(**min

**=**min

**(**x

**)**, mean

**=**mean

**(**x

**)**, max

**=**max

**(**x

**))**

**}**

It gives the following result for cars data set:

**(**cars, multi.fun

**)**

However, when I work in interactive mode I would prefer to have a function that would accept *multiple* functions as arguments. I came up with the following solution to this problem:

**<-**

**function**

**(**…

**)**

**{**

**<-**match.call

**(**expand.dots

**=**

**FALSE**

**)$**…

**<-**sapply

**(**arglist, deparse

**)**

**<-**

**(**names

**(**arglist

**)**

**!=**“”

**)**

**[**has.name

**]**

**<-**names

**(**arglist

**)[**has.name

**]**

**<-**lapply

**(**arglist, eval.parent, n

**=**2

**)**

**<-**arglist

**[[**1

**]]**

**[[**1

**]]**

**<-**

**NULL**

**<-**sapply

**(**arglist,

**function**

**(**FUN, x

**)**sapply

**(**x, FUN

**)**, x

**)**

**(**result

**)**

**<-**var.names

**[-**1

**]**

**(**result

**)**

**}**

My multi.sapply function takes a vector as first argument and next one can specify multiple functions that are to be applied to this vector. Applying it to cars data yields:

**(**cars, min, mean, max

**)**

If function argument is given name it will be used as column name instead of deparsed expression. This functionality is shown by the following example summarizing several statistics of EuStockMarkets data set:

**<-**data.frame

**(**diff

**(**log

**(**EuStockMarkets

**)))**

**(**log.returns, sd, min,

**=**

**function**

**(**x

**)**quantile

**(**x, 0.1

**))**

**leave a comment**for the author, please follow the link and comment on their blog:

**R snippets**.

R-bloggers.com offers

**daily e-mail updates**about R news and tutorials about learning R and many other topics. Click here if you're looking to post or find an R/data-science job.

Want to share your content on R-bloggers? click here if you have a blog, or here if you don't.