[R] Sth better than cycle?
Martin Maechler
maechler at stat.math.ethz.ch
Mon Dec 9 16:25:03 CET 2002
>>>>> "Ott" == Ott Toomet <otoomet at econ.dk>
>>>>> on Mon, 9 Dec 2002 11:51:25 +0100 writes:
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 <><
More information about the R-help
mailing list