# [R] mean and sd of each serial position

Sat Oct 17 02:25:02 CEST 1998

>>>>> "Bill" == Bill Simpson <wsimpson at uwinnipeg.ca> writes:

:    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

These are the "parallel mean" and "parallel standard deviation"
functions that should be part of standard R.  There is already a
"parallel maximum" function, pmax(...), for example.  In fact
there should be quite a few of these available, such as psum,
pprod, pcumsum, pdiff, ..., so if anyone has the time, feel free.

Here are two versions of pmean().  The first should be good
enough if the entire structure fits into memory; the second,
pmean.large() might be better when dealing with truly huge
vectors.  pstddev() is left as an exercise...

"pmean" <- function (..., na.rm = FALSE)  {
args <- do.call("cbind", list(...))
nargs <- ncol(args)
if (na.rm) {
OK <- !is.na(args)
args[!OK] <- 0
n <- as.vector(matrix(as.numeric(OK), nrow(args), nargs) %*%
rep(1, nargs))
}
else n <- nargs
as.vector(args %*% rep(1, nargs))/n
}

"pmean.large" <- function (..., na.rm = FALSE) {
elts <- list(...)
k <- max(unlist(lapply(elts, length)))
total <- rep(as.vector(elts[[1]]), length = k)
if (na.rm) {
n <- !is.na(total)
total[!n] <- 0
}
else {
n <- length(elts)
}
for (each in elts[-1]) {
work <- rep(as.vector(each), length = k)
if (na.rm) {
m <- is.na(work)
work[m] <- 0
n <- n + !m
}
total <- total + work
}
total/n
}

--
_________________________________________________________________
Bill Venables, Head, Dep't of Statistics,   Tel.: +61 8 8303 5418
The University of Adelaide,                 Fax.: +61 8 8303 3696
South AUSTRALIA.     5005.   Email: Bill.Venables at adelaide.edu.au
-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-
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
_._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._