[R] Matrix max by row

Bert Gunter gunter.berton at gene.com
Mon Mar 30 04:55:35 CEST 2009

If speed is a consideration,availing yourself of the built-in pmax()
function via


will be considerably faster for large matrices.

If you are puzzled by why this works, it is a useful exercise in R to figure
it out. 

Hint:The man page for ?data.frame says:
"A data frame is a list of variables of the same length with unique row
names, given class 'data.frame'."


Bert Gunter
Genentech Nonclinical Statistics

-----Original Message-----
From: r-help-bounces at r-project.org [mailto:r-help-bounces at r-project.org] On
Behalf Of Wacek Kusnierczyk
Sent: Saturday, March 28, 2009 5:22 PM
To: Ana M Aparicio Carrasco
Cc: r-help at r-project.org
Subject: Re: [R] Matrix max by row

Ana M Aparicio Carrasco wrote:
> I need help about how to obtain the max by row in a matrix.
> For example if I have the following matrix:
> 2 5 3
> 8 7 2
> 1 8 4
> The max by row will be:
> 5
> 8
> 8

matrix(apply(m, 1, max), nrow(m))


R-help at r-project.org mailing list
PLEASE do read the posting guide http://www.R-project.org/posting-guide.html
and provide commented, minimal, self-contained, reproducible code.

More information about the R-help mailing list