Outer function in R for upper triangular matrix

2019-05-16 04:34发布

问题:

I have this code currently

s1=seq(0,10,length.out=3)
s2=seq(0,10,length.out=3)
d=outer(s1,s2,`-`)
I=outer(s1,s2,`==`)

However I only want the upper triangular of d and I so I am currently doing

d=d[upper.tri(d,diag=T)]
I=I[upper.tri(I,diag=T)]

Is there a way to make this code faster through incorporating the upper triangular matrix in the outer function? Note that this is a reproducible example, however my code is much bigger and I need to decrease the running time as much as possible.

回答1:

outer internally uses rep to stretch its arguments:

    Y <- rep(Y, rep.int(length(X), length(Y)))
    if (length(X)) 
        X <- rep(X, times = ceiling(length(Y)/length(X)))

You can do the same thing using subsetting, but instead generate only the triangular indices. sequence is a useful helper function in this case:

> i <- sequence(1:3)
> j <- rep(1:3, 1:3)
> d = s1[i] - s2[j]
> I = s1[i] == s2[j]
> d
[1]   0  -5   0 -10  -5   0
> I
[1]  TRUE FALSE  TRUE FALSE FALSE  TRUE