Thank you Arthur (art297) for spending your valuable time helping me out. Your updated version indeed generates the desirable output. However, it will take me a while to digest what exactly is going on in the code and to make sure that I can comfortably apply to my large data set. I am really sorry that I have not made my inquiry very clear. Maybe the story below may shed some light: Imagine that you have two portfolios (portid 1 and 2) and company A is in both portid 1 and portid2. Portid 1 also contains Companies B and C. Portid 2 contains Companies D and E. In short, Portid 1: A, B, C Portid 2: A, D, E I am interested in calculating an average value for each company by averaging returns of companies in other portfolios. For example, average for C: (A+D+E)/3, all of which come from portid 2 (A is common) average for E: (A+B+C)/3, all of which come from portid 1 average for A in portid 1= (D+E)/2 average for A in portid 2=(B+C)/2 Overall, I have two rules: a company's average return must exclude its own return (as in A) and must only include returns from other portfolios. I hope my objective is clearer now.
... View more