[R] comparing two unequal matrices without for loop?

David Winsemius dwinsemius at comcast.net
Sun Aug 28 20:07:05 CEST 2011


On Aug 28, 2011, at 1:20 PM, Paul Hammer wrote:

> Dear folks,
>
> I would like to compare two unequal matrices.

"Unequal " is hardly an adequate data description.

> At the moment I realize
> this with two for loop and an if function but that's definitely too  
> slow
> :(...
>
> Here is my code:
>
> for (i in 1:length(all_expressed_genes[,1])) {
>   for (j in 1:length(kegg_gene_pVal[,1])) {
>     if (all_expressed_genes[j,1] == kegg_gene_pVal[i,1]) {
>       kegg_gene_pVal[j,4] =  all_expressed_genes[i,6]
>     }
>   }
> }
>
> Are there any faster solutions for that easy code?

I'm trying to figure out what this is supposed to be doing. You are  
making N^2 comparisons and transferring results from one vector of  
length N to another vector of length N. Is this really what the (non- 
existent) problem definition would have told us to do if you had  
provided a problem definition? It appears there would be a great  
possibility of overwriting earlier operations. And it appears to be  
doing N^2-N unnecessary operations as well.

> And why is R so
> dramatically slow when using for, while or other loop functions?

Blaming the tool is generally a risky idea. Axes can be used  
effectively or ineffectively. I'm guessing inadequate "operator"  
training  and/or confused problem specification.

*---------------------*
> 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
West Hartford, CT



More information about the R-help mailing list