Skip to content

Sth better than cycle?

3 messages · Ott Toomet, John Fox, Martin Maechler

#
Hi,

I want to calculate expected likelihood over a 2D discrete
distribution, something like

\sum_k \sum_l p_{kl} L(v_k, v_l)

It is trivial to write a cycle like

for(k in 1:K)
   for(l in 1:L)
      sum <- sum + p[k,l]*L(v[k], v[l])

But is there a more clever way for R?

Best wishes,

Ott
#
Dear Ott,
At 11:51 AM 12/9/2002 +0100, you wrote:

            
If the dimensions K and L are the same (isn't that implied by the common 
vector v?) then how about something like sum(p * outer(v, v, L)). If there 
are two vectors, say v1 and v2, then sum(p * outer(v1, v2, L)).

I hope that this helps,
  John
-----------------------------------------------------
John Fox
Department of Sociology
McMaster University
Hamilton, Ontario, Canada L8S 4M4
email: jfox at mcmaster.ca
phone: 905-525-9140x23604
web: www.socsci.mcmaster.ca/jfox
-----------------------------------------------------
#
Ott> Hi,
    Ott> I want to calculate expected likelihood over a 2D discrete
    Ott> distribution, something like

    Ott> \sum_k \sum_l p_{kl} L(v_k, v_l)

    Ott> It is trivial to write a cycle like

    Ott> for(k in 1:K)
    Ott>  for(l in 1:L)
    Ott>    sum <- sum + p[k,l]*L(v[k], v[l])

    Ott> But is there a more clever way for R?

"more clever" meaning "faster", right?

Well, this really depends if L(.,.) is vectorized,
i.e. when x1 and x2 are vectors of length n,  
     r <- L(x1,x2) is of lenghth n with the proper values?

If this is the case, {something like} the following should work:

   n <- length(v)
   v1 <- rep(v, n)
   v2 <- rep(v, each = n)  
   
   sum(p * L(v1,v2)) ## or L(v2,v1) if it matters

Note that above,  
cbind(v1,v2)    is really a (fast no-names) version of 
expand.grid(v,v)

Hoping this helps,
Martin

Martin Maechler <maechler at stat.math.ethz.ch>	http://stat.ethz.ch/~maechler/
Seminar fuer Statistik, ETH-Zentrum  LEO C16	Leonhardstr. 27
ETH (Federal Inst. Technology)	8092 Zurich	SWITZERLAND
phone: x-41-1-632-3408		fax: ...-1228			<><