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" <[EMAIL PROTECTED]> To: <[EMAIL PROTECTED]> 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 > [EMAIL PROTECTED] (edit in obvious way; spam precaution) > > ______________________________________________ > [EMAIL PROTECTED] 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 ______________________________________________ [EMAIL PROTECTED] 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
