[R] Efficient lookup on a two-dimensional table

David Winsemius dwinsemius at comcast.net
Thu Jun 25 16:25:24 CEST 2009


On Jun 25, 2009, at 10:02 AM, Rama Ramakrishnan 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
>

?apply

x$value <- apply(y, 1, function(z) x[ z['ltrs'], z['mnths'] ])

> #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 at 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.

David Winsemius, MD
Heritage Laboratories
West Hartford, CT




More information about the R-help mailing list