# [R] mean and sd of each serial position

Thomas Lumley thomas at biostat.washington.edu
Fri Oct 16 20:32:28 CEST 1998

```On Fri, 16 Oct 1998, Bill Simpson wrote:

> I want to do something like this in R. If I have three vectors
> > a1
> [1] 1 2 3
> > a2
> [1] 4 5 6
> > a3
> [1] 9 10 7
>
> I want to compute
> 1. A vector that is the mean at each serial position of a1, a2, and a3.
> so in this example it would have the contents
> 4.667, 5.667, 5.333333
>
> 2. A vector that is the SD at each serial position of a1, a2, and a3.
> so in this example it would have the contents
>  4.041452, 4.041452, 2.081666
>
> Can anyone tell me a good way to do this in R? The only thing I can come
> up with is

Use apply():

cbind(a1,a2,a3) makes matrix

apply(cbind(a1,a2,a3),1,mean) computes the mean of each row of the matrix

In general you can do

meanvec<-function (...)
apply(cbind(...), 1, mean)

and then
R> a1<-1:10
R> a2<-2:11
R> a3<-3:12
R> meanvec(a1,a2,a3)
[1]  2  3  4  5  6  7  8  9 10 11

This doesn't check that all the vectors are the same length. A more
sophisticated version is
meanvec<-function (...) {
if (length(unique(sapply(list(...),length)))!=1)
stop("not all same length")
apply(cbind(...), 1, mean)
}

R> meanvec(a1,a2,a3)
[1]  2  3  4  5  6  7  8  9 10 11
R> a4<-1:3
R> meanvec(a1,a2,a3,a4)
Error: not all same length

Thomas Lumley
------------------------------------------------------+------
Biostatistics		: "Never attribute to malice what  :
Uni of Washington	:  can be adequately explained by  :
Box 357232		:  incompetence" - Hanlon's Razor  :
Seattle WA 98195-7232	:				   :
------------------------------------------------------------

-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-
r-help mailing list -- Read http://www.ci.tuwien.ac.at/~hornik/R/R-FAQ.html
Send "info", "help", or "[un]subscribe"
(in the "body", not the subject !)  To: r-help-request at stat.math.ethz.ch
_._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._

```