简体   繁体   中英

coding double sum in R

I would like to compute these to quantities

a12=sum_(i from 1 to m)sum_(j1<j2)(I(X[i]>Y[j1] and X[i]>Y[j2]))

a13=sum_(j from 1 to n)sum_(i1<i2)(I(X[i1]>Y[j] and X[i2]>Y[j]))

where I is the indicator function.

So I came up with this R code

a12=0; a13=0

for (l in 1:(length(Z1)-1)){

 for (m in  1:(length(Z2)-1)){

 a12<-a12+(Z1[l]<Z2[m])*(Z1[l+1]<Z2[m])*1

 a13<-a13+(Z1[l]<Z2[m])*(Z1[l]<Z2[m+1])*1

        } # closing m

          } # closing l

    a12=a12+sum((Z1[-length(Z1)]<Z2[length(Z2)])*(Z1[-1]<Z2[length(Z2)])*1)

    a13=a13+sum((Z1[length(Z1)]<Z2[-length(Z2)])*(Z1[length(Z1)]<Z2[-1])*1)


a12;
a13

Unfortunately, not only this is very slow but I am not getting what I am supposed to get.

Could you help me, please!

Thanks,

Roland

I'm assuming (for a12 ) you want to do the following. You have two vectors x (of length m ) and y , and for each element x[i] of x , you are calculating the number of distinct index pairs j1 , j2 of y such that x[i] exceeds both y[j1] and y[j2] , and then you are summing this quantity over all i . Here's a fast way to do a12 (the other will be left as an exercise). First note that you can flip the order of summation:

a12 = Sum_(j1 < j2) Sum_(i=1:m) I( X[i] > Y[j1] & X[i] > Y[j2] ),

ie for each distinct index-pair j1,j2 , we calculate the number of x elements that exceed both y[j1] and y[j2] , and then we sum this quantity over all these distinct index-pairs. Now calculating the inner sum for pairs j1,j2 is like a matrix multiplication. Indeed, suppose we define vectors x and y :

set.seed(1)
x <- sample(1:5,5,T)
y <- sample(1:5,10,T)

then we can use the outer function to produce a matrix y_x whose [i,j] entry is TRUE if and only if y[i] < x[j] :

y_x <- outer(y,x,FUN = '<')

Now we get the inner sums by doing

z <- y_x %*% t(y_x)

where z[i,j] is the number of elements of x that exceed both y[i] and y[j] . Since we only want to sum z[i,j] for distinct i < j , we get the final result by taking the sum of the lower-triangle of z using

a12 <- sum( z[lower.tri( z )])

> a12
[1] 72

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM