Austen
Austen

Reputation: 65

Custom tcrossprod function in R

I am using the tcrossprod function on a matrix in R. It does a cross product of my data and its transpose. i.e. data %*% t(data).

The problem is, I don't want the individual operations (between rows in data and columns in t(data)) to be multiplication operations. Is it possible to specify my own function in there so that the same algorithm is implemented but it does something else instead of multiplication.

I am achieving the same result now by looping through the matrices and performing the required operation but the looping makes this approach slow.

Here's what I am currently doing (but replacing the * operation with something else):

count<-nrow(data)
output<-sapply(1:count, function(x){
        sapply(1:count, function(y){
                sum((data[x,]+data[y,])*abs(data[x,]-data[y,]))
            })
    })

Any help would be much appreciated.

Upvotes: 3

Views: 643

Answers (1)

flodel
flodel

Reputation: 89057

This will replace one of your slow sapply loop with much faster matrix operations:

sapply(1:count, function(i, x) {
   colSums((x + x[, i]) * abs(x - x[, i]))} , x = t(data))

And to make that a tiny bit faster, replace sapply with vapply:

vapply(1:count, function(i, x) {
   colSums((x + x[, i]) * abs(x - x[, i]))} , numeric(count), x = t(data))

If this is still too slow for you, then most likely a Rcpp solution will do. Otherwise I do not see a base-only solution that would be significantly faster than this (I'd be glad to be proven wrong though.)

Upvotes: 2

Related Questions