Given: > mitest <- matrix(1:16,ncol=4) > dimnames(mitest)[[1]] <- c("a","b","c","d") > dimnames(mitest)[[2]] <- c("a","b","c","d") > mitest a b c d a 1 5 9 13 b 2 6 10 14 c 3 7 11 15 d 4 8 12 16 I can do: > mitest[cbind(c(1,2,3),c(2,3,2))] [1] 5 10 7 but using the names does not work: > mitest[cbind(c("a","b","c"),c("b","c","b"))] [1] NA NA NA NA NA NA despite the fact that > mitest["a","b"] [1] 5 works fine. How can I do the equivalent of > mitest[cbind(c(1,2,3),c(2,3,2))] using row and column names? Thanks Agus -- Dr. Agustin Lobo Institut de Ciencies de la Terra "Jaume Almera" (CSIC) LLuis Sole Sabaris s/n 08028 Barcelona Spain Tel. 34 934095410 Fax. 34 934110012 email: Agustin.Lobo at ija.csic.es http://www.ija.csic.es/gt/obster
Henrique Dallazuanna
2009-Sep-02 16:49 UTC
[R] Problem at subsetting matrix by using dimnames
Try this: mapply(function(x, y)mitest[x, y], c("a", "b", "c"), c("b", "c", "b")) or diag(`[`(mitest, i = c("a", "b", "c"), j = c("b", "c", "b"))) On Wed, Sep 2, 2009 at 6:57 AM, Agustin Lobo <aloboaleu@gmail.com> wrote:> Given: > > > mitest <- matrix(1:16,ncol=4) > > dimnames(mitest)[[1]] <- c("a","b","c","d") > > dimnames(mitest)[[2]] <- c("a","b","c","d") > > mitest > a b c d > a 1 5 9 13 > b 2 6 10 14 > c 3 7 11 15 > d 4 8 12 16 > > I can do: > > mitest[cbind(c(1,2,3),c(2,3,2))] > [1] 5 10 7 > > but using the names does not work: > > mitest[cbind(c("a","b","c"),c("b","c","b"))] > [1] NA NA NA NA NA NA > > despite the fact that > > mitest["a","b"] > [1] 5 > > works fine. > > How can I do the equivalent of > > mitest[cbind(c(1,2,3),c(2,3,2))] > > using row and column names? > > Thanks > > Agus > > > -- > Dr. Agustin Lobo > Institut de Ciencies de la Terra "Jaume Almera" (CSIC) > LLuis Sole Sabaris s/n > 08028 Barcelona > Spain > Tel. 34 934095410 > Fax. 34 934110012 > email: Agustin.Lobo@ija.csic.es > http://www.ija.csic.es/gt/obster > > ______________________________________________ > R-help@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. >-- Henrique Dallazuanna Curitiba-Paraná-Brasil 25° 25' 40" S 49° 16' 22" O [[alternative HTML version deleted]]