Try this (shown for stated problem but generalizes by just adding additional arguments):
mapply("[", list(x), ltrs, mnths) On Thu, Jun 25, 2009 at 10:24 AM, Rama Ramakrishnan<r...@alum.mit.edu> wrote: > Follow-on question: is there a way to do this for higher-dimensional (i.e. > more than 2 dimensions) arrays? > > > On Thu, Jun 25, 2009 at 10:17 AM, Rama Ramakrishnan <r...@alum.mit.edu>wrote: > >> That works!! Very nice way to do it! Thank you, Henrique! >> Rama Ramakrishnan >> >> >> On Thu, Jun 25, 2009 at 10:11 AM, Henrique Dallazuanna >> <www...@gmail.com>wrote: >> >>> Try this: >>> >>> y$values <- diag(x[y$ltrs, y$mnths]) >>> >>> On Thu, Jun 25, 2009 at 11:02 AM, Rama Ramakrishnan >>> <r...@alum.mit.edu>wrote: >>> >>>> Dear R-Users, >>>> I need to lookup values from a 2-d table using the row names and column >>>> names as indices. I was wondering if there's a way to do this without an >>>> explicit loop. >>>> >>>> Example: >>>> #x is the 2-d table that holds the values >>>> >>>> x <- matrix(rnorm(26*12),nrow=26) >>>> >>>> rownames(x) <- letters >>>> >>>> colnames(x) <- month.name >>>> >>>> >>>> #y is a data frame that has the "keys" I want to use as indices into x >>>> >>>> y <- data.frame(ltrs=sample(letters,5),mnths=sample(month.name >>>> ,5),values=0) >>>> >>>> >>>> #I want to fill in the "values" column using the "ltrs" and "mnths" >>>> columns >>>> as keys to look up >>>> >>>> # the associated value from x >>>> >>>> #One way to do this is with a FOR loop >>>> >>>> for (i in 1:nrow(y)) {y$val[i] <- x[y$ltrs[i],y$mnths[i]]} >>>> >>>> >>>> My question: Is there a more efficient way (e.g., one without using an >>>> explicit loop) to do this? >>>> >>>> >>>> Thanks in advance! >>>> >>>> >>>> -Rama Ramakrishnan >>>> >>>> [[alternative HTML version deleted]] >>>> >>>> ______________________________________________ >>>> 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]] > > > ______________________________________________ > 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. > > ______________________________________________ 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.