[R] Basic matrix manipulation problem

Petr Savicky savicky at cs.cas.cz
Wed Apr 25 07:48:18 CEST 2012


On Tue, Apr 24, 2012 at 01:36:25PM -0700, Hans Thompson wrote:
> Hello, this forum was very helpful yesterday with a simple question I had on
> working with tables.   What function will I need to use to do the following.
> 
> Move matrix a:
> 
>        A    B   C   D
> x    1    2    3    4
> y    5    6    7    8
> 
> to the mean of B&C and C&D:
> 
>       BC  CD  
> x   2.5  3.5
> y   6.5  7.5
> 
> and then to the mean of B&CB, C&BC, C&CD, and D&CD:
> 
>      AAB  BAB  CCD  DCD
> x  1.75  2.25  3.25  3.75
> y  6.25  6.75  7.25  7.75

Hi.

Try the following.

  # initial matrix
  a <- matrix(1:8, nrow=2, byrow=TRUE)
  dimnames(a) <- list(c("x","y"), LETTERS[1:4])

  #create new matrix
  b <- cbind(BC=(a[,"B"]+a[,"C"])/2, CD=(a[,"C"]+a[,"D"])/2)
  b

     BC  CD
  x 2.5 3.5
  y 6.5 7.5

The next step may be done similarly using cbind(AAB=..., BAB=...).

Hope this helps.

Petr Savicky.



More information about the R-help mailing list