[R] summation coding

Berend Hasselman bhh at xs4all.nl
Fri Oct 19 10:53:02 CEST 2012


On 19-10-2012, at 10:38, Berend Hasselman wrote:

> 
> On 18-10-2012, at 21:33, djbanana wrote:
> 
>> I would like to code the following in R: a1(b1+b2+b3) + a2(b1+b3+b4) +
>> a3(b1+b2+b4) + a4(b1+b2+b3)
>> 
>> or in summation notation: sum_{i=1, j\neq i}^{4} a_i * b_i
>> 
>> I realise this is the same as: sum_{i=1, j=1}^{4} a_i * b_i - sum_{i=j} a_i
>> * b_i
>> 
> 
> This is partly TeX notation not summation notation, whatever that may be.
> And these "sums" make no sense: where is index j used in the first? where is it used in the second?
> 
> Solutions starting from you explicit formula, from slowest to fastest
> 
> sum( outer(a,b,"*") ) - sum(a*b)
> sum(sapply(1:length(a),function(k) a[k]*sum(b[-k])))
> sum(convolve(a,b)) - sum(a*b)   # sum(convolve(a,rev(b), type="o")) - sum(a*b)
> 

And from Nabble another solution (not posted to the R-help list (yet?) ) which turns out to be the quickest (obviously)

sum(a*(sum(b)-b)) 

Berend

> Berend
> 
> 
>> would appreciate some help.
>> 
>> Thank you.
>> 
>> 
>> 
>> --
>> View this message in context: http://r.789695.n4.nabble.com/summation-coding-tp4646678.html
>> Sent from the R help mailing list archive at Nabble.com.
>> 
>> ______________________________________________
>> 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.
> 
> ______________________________________________
> 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.




More information about the R-help mailing list