# Re: [R] how to do pairwise sums in a matrix

From: Jorge Ivan Velez <jorgeivanvelez_at_gmail.com>
Date: Wed, 21 May 2008 14:04:27 -0400

Hi Gregory,
Try this:

cs=substr(colnames(Mat),1,1)
res=t(apply(t(Mat),2,tapply,cs,sum,na.rm=TRUE)) dim(res)
 50 5

HTH, Jorge

On Wed, May 21, 2008 at 1:22 PM, Gregory Gentlemen < gregory_gentlemen_at_yahoo.ca> wrote:

> I am looking for an efficient way to solve the following problem. I have a
> large matrix of continuous values with a small proportion of missing values.
> Columns correspond to variables where each variable has two measurements,
> call them A and B. The matrix is such that the columns are in sequence with
> respect to the variables. I would like to sum up the two measurements for
> each variable and each observation (the rows) for the whole matrix. Here is
> an example of such a matrix with 5 variables (R, S, T, U, V) and 50
> observations:
>
> set.seed(27)
> Mat <- matrix(rnorm(500), nrow=50, ncol=10)
> dimnames(Mat)[] <-
> c("R.A","R.B","S.A","S.B","T.A","T.B","U.A","U.B","V.A","V.B")
>
> miss.ind <- rbinom(500,1,prob=0.98)
> Mat[!as.logical(miss.ind)] <- NA
>
> So I would like to produce 50 by 5 matrix where the columns are the sums of
> A+B measurements for each of the 5 variables.
>
> Thanks for any help.
>
> Gregory Gentlemen
>
>
> ---------------------------------
>
> [[alternative HTML version deleted]]
>
> ______________________________________________
> R-help_at_r-project.org mailing list
> https://stat.ethz.ch/mailman/listinfo/r-help
> http://www.R-project.org/posting-guide.html
> and provide commented, minimal, self-contained, reproducible code.
>

[[alternative HTML version deleted]]

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. Received on Wed 21 May 2008 - 18:22:25 GMT

Archive maintained by Robert King, hosted by the discipline of statistics at the University of Newcastle, Australia.
Archive generated by hypermail 2.2.0, at Wed 21 May 2008 - 18:30:39 GMT.

Mailing list information is available at https://stat.ethz.ch/mailman/listinfo/r-help. Please read the posting guide before posting to the list.