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

arun smartpink111 at yahoo.com
Thu Dec 27 02:11:05 CET 2012


Hi,
Try this:
 sapply(iris[,-5],function(x) rbind(mean(x,na.rm=T),sd(x,na.rm=T)))
#     Sepal.Length Sepal.Width Petal.Length Petal.Width
#[1,]    5.8433333   3.0573333     3.758000   1.1993333
#[2,]    0.8280661   0.4358663     1.765298   0.7622377
A.K.




----- Original Message -----
From: Yao He <yao.h.1988 at gmail.com>
To: r-help at r-project.org
Cc: 
Sent: Wednesday, December 26, 2012 7:54 PM
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