[R] how to do calculations in data matrices?

Dan Davison davison at stats.ox.ac.uk
Sat Feb 13 20:45:33 CET 2010


Zoppoli, Gabriele (NIH/NCI) [G] <zoppolig <at> mail.nih.gov> writes:

> 
> Please give me just a reference where I can find something useful. 

The others are right that rather than randomly googling, you should bite
the bullet and sit down for a couple of hours with some introductory
material on R (a book, or one of the freely available pdfs). Unless you are
never going to use R again, it will be worth it. But seeing as you asked your
question clearly, here's one
way to do the steps you specify. Hopefully this will help as well.

First, make a matrix to work with:

> mat1 <- matrix(sample(1:10, size=12, replace=TRUE), ncol=4)
> mat1
     [,1] [,2] [,3] [,4]
[1,]    5    7   10    9
[2,]    4   10    8    2
[3,]    8   10    9    5

> 
> 
> In summary, I need to :
> 
> - find the median of each row of a matrix

You can use apply for that:

> row.medians <- apply(mat1, 1, median)
> row.medians
[1] 8.0 6.0 8.5

> - create a new matrix with each value in the first matrix divided by
> the median of its row

That's easy to *do*:

> mat2 <- mat1 / row.medians
> mat2
          [,1]     [,2]     [,3]      [,4]
[1,] 0.6250000 0.875000 1.250000 1.1250000
[2,] 0.6666667 1.666667 1.333333 0.3333333
[3,] 0.9411765 1.176471 1.058824 0.5882353

but it may take more time to understand why that worked. How come it
knew that we wanted to divide each row by the median of the row? (Hint:
understand the "byrow" argument in ?matrix and the mentions of the word
"recyling" in ?Arithmetic).

> - if a value "a" in the second matrix is < 1, I need to substitute it
> with 1/a

First make a logical vector which identifies the elements of the matrix
you want to operate on:
> is.small <- mat2 < 1

Then perform the operation on those elements:

> mat2[is.small] <- 1 / mat2[is.small]
> mat2
       [,1]     [,2]     [,3]  [,4]
[1,] 1.6000 1.142857 1.250000 1.125
[2,] 1.5000 1.666667 1.333333 3.000
[3,] 1.0625 1.176471 1.058824 1.700


# you could also use
ifelse(mat2 < 1, 1/mat2, mat2)

dan

> 
> I know that for some of you it must be overeasy, but I swear I googled
> for two hours with keywords "operations", "calculations", "data
> matrices", "data tables", and "CRAN", and I didn't find anything
> useful.
> 
> Thank you all
> 
> Gabriele Zoppoli, MD
> Ph.D. Fellow, Experimental and Clinical Oncology and Hematology,
> University of Genova, Genova, Italy
> Guest Researcher, LMP, NCI, NIH, Bethesda MD
> 
> Work: 301-451-8575
> Mobile: 301-204-5642
> Email: zoppolig <at> mail.nih.gov
>



More information about the R-help mailing list