[R] rownames of single row matrices

Dimitris Rizopoulos dimitris.rizopoulos at med.kuleuven.ac.be
Fri Jun 11 10:14:43 CEST 2004


Dear Robin,

I think you just need:

a[1,,drop=F]

Best,
Dimitris

----
Dimitris Rizopoulos
Doctoral Student
Biostatistical Centre
School of Public Health
Catholic University of Leuven

Address: Kapucijnenvoer 35, Leuven, Belgium
Tel: +32/16/396887
Fax: +32/16/337015
Web: http://www.med.kuleuven.ac.be/biostat/
     http://www.student.kuleuven.ac.be/~m0390867/dimitris.htm



----- Original Message ----- 
From: "Robin Hankin" <rksh at soc.soton.ac.uk>
To: <r-help at stat.math.ethz.ch>
Sent: Friday, June 11, 2004 10:09 AM
Subject: [R] rownames of single row matrices


> Hi
>
> I want to extract rows of a matrix, and preserve rownames even if
only
> one row is selected.  Toy example:
>
> R> a <- matrix(1:9,3,3)
> R> rownames(a) <- letters[1:3]
> R> colnames(a) <- LETTERS[1:3]
> R> a
>    A B C
> a 1 4 7
> b 2 5 8
> c 3 6 9
>
>
> Extract the first two rows:
> R> wanted <- 1:2
> R> a[wanted,]
>    A B C
> a 1 4 7
> b 2 5 8
>
> rownames come through fine.  Now extract just
> one row:
>
> R> a[1,]
> A B C
> 1 4 7
>
>
> rowname is lost!  (also note that this isn't a 1-by-n matrix as
> needed.  This object
> is a vector). How do I get the rowname back?
> My best effort is:
>
> extract <- function(a,wanted){
>    if(length(wanted)>1) {
>       return(a[wanted,])
>    } else {
>       out <- t(as.matrix(a[wanted,]))
>       rownames(out) <- rownames(a)[wanted]
>       return(out)
>    }
> }
>
> [note the transpose and as.matrix()].  There must be a better way!
> Anyone got any better ideas?
>
> What is the R rationale for treating a[1,] so differently from
a[1:2,]  ?
>
>
> -- 
> Robin Hankin
> Uncertainty Analyst
> Southampton Oceanography Centre
> SO14 3ZH
> tel +44(0)23-8059-7743
> initialDOTsurname at soc.soton.ac.uk (edit in obvious way; spam
precaution)
>
> ______________________________________________
> R-help at stat.math.ethz.ch mailing list
> https://www.stat.math.ethz.ch/mailman/listinfo/r-help
> PLEASE do read the posting guide!
http://www.R-project.org/posting-guide.html




More information about the R-help mailing list