Hi Robin

Have a look at:

> help("[")

The fact that dimensions are lost when extracting is a feature of the language.

What you need is the "drop" option.

> a[1,,drop=FALSE]
  A B C
a 1 4 7

Eric

At 10:09 11/06/2004, Robin Hankin wrote:
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

Reply via email to