[R] how to get row name using the which function

Downey, Patrick PDowney at urban.org
Mon May 2 15:04:57 CEST 2011


Perhaps not the most elegant. 

rownames(example)[which.max(example)]

If you wanted to type less, you could always write a function.

names.max <- function(x){
  return(rownames(example)[which.max(example)])
}


-Mitch


-----Original Message-----
From: r-help-bounces at r-project.org [mailto:r-help-bounces at r-project.org] On
Behalf Of Schumacher, G.
Sent: Monday, May 02, 2011 7:54 AM
To: 'r-help at r-project.org'
Subject: [R] how to get row name using the which function

Dear All,

Probably a very basic question, but can't seem to work my way around it.

I want to which row has the maximum value. But what if the row names do not
correspond with the row numbers. In the example below, you'll see that the
max of example is row 4, but the name of row 4 is "9". How do I get R to
return "9" as value, instead of 4.

example <- matrix(c(0,0,0,1), 4, 1, dimnames=list(c("1", "3", "5", "9"),
c("1")))
which.max(example)

[1] 4

Hope someone can help out.

Gijs Schumacher, MSc
PhD candidate

--------------------------------------
Department of Political Science
VU University Amsterdam

Contact:
Tel: +31(0)20 5986798
Fax: +31(0)20 5986820
Web: http://home.fsw.vu.nl/g.schumacher
Email: g.schumacher at vu.nl<mailto:g.schumacher at fsw.vu.nl>

Visiting address:
Metropolitan
Buitenveldertselaan 2
Room Z - 333

Mail:
De Boelelaan 1081
1081 HV Amsterdam
The Netherlands


	[[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.



More information about the R-help mailing list