Note that there are some explanatory texts on larger screens.

plurals
  1. POR - vectorizing a which operation
    primarykey
    data
    text
    <p>Hi I have a function in R that I'm trying to optimize for performance. I need to vectorize a for loop. My problem is the slightly convoluted data structure and the way I need to perform lookups using the 'which' command.</p> <p>Lets say we are dealing with 5 elements (1,2,3,4,5), the 10x2 matrix pairs is a combination of all unique pairs the 5 elements (i.e. (1,2), (1,3),(1,4) ....(4,5)). all_prods is a 10x1 matrix that I need to look up using the pairs while iterating through all the 5 elements. </p> <p>So for 1, I need to index rows 1, 2, 3, 4 (pairs 1,2 1,3 1,4 and 1,5) from all_prods and so on for 1, 2, 3, 4, 5.</p> <p>I have only recently switched to R from matlab so would really appreciate any help.</p> <pre><code>foo &lt;- function(AA , BB , CC ){ pa &lt;- AA*CC; pairs &lt;- t(combn(seq_len(length(AA)),2)); all_prods &lt;- pa[pairs[,1]] * pa[pairs[,2]]; result &lt;- matrix(0,1,length(AA)); # WANT TO VECTORIZE THIS BLOCK for(st in seq(from=1,to=length(AA))){ result[st] &lt;- sum(all_prods[c(which(pairs[,1]==st), which(pairs[,2]==st))])*BB[st]; } return(result); } AA &lt;- seq(from=1,to=5); BB&lt;-seq(from=11,to=15); CC&lt;-seq(from=21,to=25); results &lt;- foo(AA,BB,CC); #final results is [7715 164208 256542 348096 431250] </code></pre> <p>I want to convert the for loop into a vectorised version. Instead of looping through every element st, I'd like to do it in one command that gives me a results vector (rather than building it up element by element)</p> <p>Thanks in advance.</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload