[R] how to apply two or more functions to each columns in a time?

Pete Brecknock Peter.Brecknock at bp.com
Thu Dec 27 02:56:57 CET 2012


Yao He wrote
> 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@

> ——————————————————————————
> 
> ______________________________________________

> R-help@

>  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.

Or maybe using apply ....

# data
d <- iris[,-5]

# apply function
a <-data.frame(apply(d, 2, function(x) c(mean=mean(x), sd=sd(x))))

# print(a) output
     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

HTH

Pete





--
View this message in context: http://r.789695.n4.nabble.com/how-to-apply-two-or-more-functions-to-each-columns-in-a-time-tp4654001p4654004.html
Sent from the R help mailing list archive at Nabble.com.




More information about the R-help mailing list