[R] How do you apply a function to each variable in a data frame?

hadley wickham h.wickham at gmail.com
Mon Nov 3 18:08:06 CET 2008


On Mon, Nov 3, 2008 at 9:02 AM, Jorge Ivan Velez
<jorgeivanvelez at gmail.com> wrote:
> Dear zerftezen,
> Try this:
>
> # Data
> set.seed(123)
> X=as.data.frame(matrix(rnorm(100),ncol=10))
>
> # Percentiles 10 and 90 using apply
> t(apply(X,2,quantile,probs=c(0.1,0.9)))
>
> # The same using sapply
> t(sapply(X,function(x) quantile(x,probs=c(0.1,0.9))))

An alternative is the colwise function in the plyr package:

library(plyr)
colwise(quantile)(X, probs = c(0.1,0.9))
colwise(quantile)(mtcars,  probs = c(0.1,0.9))

It always returns a data frame.  You can also use catcolwise and
numcolwise which only operate on categorical and numeric columns
respectively.

Hadley

-- 
http://had.co.nz/



More information about the R-help mailing list