[R] Usage of apply

Chuck Cleland ccleland at optonline.net
Wed Dec 6 15:53:55 CET 2006


Jin Shusong wrote:
> Dear R Users,
>   
>   Are there any documents on the usage of apply, tapply,
> sapply so that I avoid explicit loops.  I found that these
> three functions were quite hard to be understood.  Thank you
> in advance.

  If you have read the help pages for each and possibly even consulted
the reference on those help pages, you may need to elaborate on what
parts of these functions you don't understand.  You might also describe
a loop you are contemplating and ask how it might be replaced by one of
these functions.
  Here is a very simple example of a loop that could be avoided with one
of these functions:

> for(i in 1:4){print(mean(iris[,i]))}
[1] 5.843333
[1] 3.057333
[1] 3.758
[1] 1.199333

  Here is how you would do that with apply():

> apply(iris[,1:4], 2, mean)
Sepal.Length  Sepal.Width Petal.Length  Petal.Width
    5.843333     3.057333     3.758000     1.199333

  Even better in this particular case would be:

> colMeans(iris[,1:4])
Sepal.Length  Sepal.Width Petal.Length  Petal.Width
    5.843333     3.057333     3.758000     1.199333

  but you don't always want mean() or sum() as the function, so the
functions you mention above are more general than colMeans() and similar
functions.

> 
> ------------------------------------------------------------------------
> 
> ______________________________________________
> R-help at stat.math.ethz.ch mailing list
> https://stat.ethz.ch/mailman/listinfo/r-help
> PLEASE do read the posting guide http://www.R-project.org/posting-guide.html
> and provide commented, minimal, self-contained, reproducible code.

-- 
Chuck Cleland, Ph.D.
NDRI, Inc.
71 West 23rd Street, 8th floor
New York, NY 10010
tel: (212) 845-4495 (Tu, Th)
tel: (732) 512-0171 (M, W, F)
fax: (917) 438-0894




More information about the R-help mailing list