Custom function tcrossprod in R

I am using the tcrossprod function on a matrix in R. It does the cross product of my data and transpose it. that is, data% *% t (data).

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

Now I get the same result by looping through the matrices and doing the operation I want, but the loop makes this approach slow.

Here's what I'm doing now (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.

+3


source to share


1 answer


This will replace one of the slower loops sapply

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 it a little 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 it will be Rcpp's solution. Otherwise, I don't see a basic solution that is significantly faster than this (I'd be glad to be wrong though.)

+2


source







All Articles