Date: Sat, 17 Oct 1998 09:55:02 +0930
Message-Id: <9810170025.AA11564@attunga.stats.adelaide.edu.au>
From: Bill Venables <wvenable@attunga.stats.adelaide.edu.au>
To: Bill Simpson <wsimpson@uwinnipeg.ca>
Subject: Re: [R] mean and sd of each serial position
In-Reply-To: <Pine.OSF.3.95.981016122938.5528A-100000@io.uwinnipeg.ca>
>>>>> "Bill" == Bill Simpson <wsimpson@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@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@stat.math.ethz.ch _._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._