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

Erik Iverson iverson at biostat.wisc.edu
Mon Nov 3 19:24:26 CET 2008

zerfetzen wrote:
> I want to apply a more complicated function than what I use in my example,
> but the idea is the same:
> Suppose you have a data frame named x and you want to a function applied to
> each variable, we'll just use the quantile function for this example.  I'm
> trying all sorts of apply functions, but not having luck.  My best guess
> would be:
> sapply(x, FUN=quantile)

And how does that not work?  For me, it does:

test <- data.frame(a = rnorm(100), b = rnorm(100), c = rnorm(100))
sapply(test, quantile)

You should say what you tried and most importantly, *how* you are not 
having luck, i.e., what errors or unexpected results you are getting.

Using small examples like the 'test' data.frame can also help clear up 

More information about the R-help mailing list