[R] rownames of single row matrices
Robin Hankin
rksh at soc.soton.ac.uk
Fri Jun 11 10:09:19 CEST 2004
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)
More information about the R-help
mailing list