Rik
Rik

Reputation: 1987

Tapply over matrix using matrix math

All, I have the following code, I'd like to make it generalized for more clusters, ie C clusters. Is there a way to do this without a loop? Here, the rows of X correspond to variables x1,x2, and T is a linear transformation of X. Thanks.

X=matrix(c(2,3,4,5,6,7,8,9,2,3,4,5,6,7,8,9),2)
cluster=c(1,1,1,0,0,0,0,0)
T=matrix(c(1,2,2,1),2)
f<-function(x) max(eigen(t(x)%*%x)$values)
f(T%*%X[,cluster==0])+f(T%*%X[,cluster==1])
## [1] 1134.87

I was thinking of

  sum(tapply(X,cluster,function(x) f(T%*%x)))

but I get this error, I think because tapply takes a vector vs matrix:

> sum(tapply(X,cluster,function(x) f(T%*%x)))
Error in tapply(X, cluster, function(x) f[x]) : 
  arguments must have same length

Here is an answer with a for loop, if you can find something without a loop please let me know

 #
    c=length(levels(factor(cluster)))
    cluster=factor(cluster,labels=1:c)
    s=0
    for (i in 1:c){
    s=s+f(T%*%X[,cluster==c])
    }
    s
    ## [1] 1134.872

Upvotes: 2

Views: 528

Answers (1)

nicola
nicola

Reputation: 24490

Could try doing this via tapply

tapply(seq_len(ncol(X)), cluster, function(x) f(T%*%X[, x])) 
#        0        1 
# 3840.681 1238.826 

Upvotes: 1

Related Questions