[R] how to apply two or more functions to each columns in a time?
David L Carlson
dcarlson at tamu.edu
Thu Dec 27 02:29:36 CET 2012
Combine the functions with rbind(). If there are more than two, it will
probably be easier to define the function outside sapply.
> dta <- sapply(iris[,-5],function(x) rbind(mean(x,na.rm=T), sd(x,na.rm=T)))
> rownames(dta) <- c("mean", "SD")
> dta
Sepal.Length Sepal.Width Petal.Length Petal.Width
mean 5.8433333 3.0573333 3.758000 1.1993333
SD 0.8280661 0.4358663 1.765298 0.7622377
----------------------------------------------
David L Carlson
Associate Professor of Anthropology
Texas A&M University
College Station, TX 77843-4352
> -----Original Message-----
> From: r-help-bounces at r-project.org [mailto:r-help-bounces at r-
> project.org] On Behalf Of Yao He
> Sent: Wednesday, December 26, 2012 6:54 PM
> To: r-help at r-project.org
> Subject: [R] how to apply two or more functions to each columns in a
> time?
>
> Dear All:
>
> I want to calculate the mean and sd for each column in a data.frame.
>
> Taking data(iris) for example:
> I tried sapply(iris[,-5],mean,na.rm=T) or sapply(iris[,-5],sd,na.rm=T)
> to calculate the mean and sd .But sapply() transfer a function per
> time. How to transfer two functions in a time to generate a data.frame
> like this:
>
> Sepal.Length Sepal.Width Petal.Length Petal.Width
> mean 5.84333 3.05733 3.758000 1.199333
> SD 0.82806 0.43586 1.765298 0.762237
>
>
> Thanks a lot
>
> Yao He
>
> --
> -------------------------
> Master candidate in 2rd year
> Department of Animal genetics & breeding
> Room 436,College of Animial Science&Technology,
> China Agriculture University,Beijing,100193
> E-mail: yao.h.1988 at gmail.com
> --------------------------
>
> ______________________________________________
> R-help at r-project.org 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.
More information about the R-help
mailing list