2

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
Rik
  • 1,870
  • 3
  • 22
  • 35
  • You should call `f` with round brackets, `f()` – Frank Apr 27 '15 at 17:51
  • No, T%*%X is not square, that is why f is taking t(x)%*%x to make a square matrix. T is a linear transformation of X and I'm looking at how this effects the principal components of the clusters which are numbered 0 and 1. – Rik Apr 27 '15 at 18:15

1 Answers1

1

Could try doing this via tapply

tapply(seq_len(ncol(X)), cluster, function(x) f(T%*%X[, x])) 
#        0        1 
# 3840.681 1238.826 
David Arenburg
  • 91,361
  • 17
  • 137
  • 196
nicola
  • 24,005
  • 3
  • 35
  • 56
  • very nice! I used sum(sapply(split(t(X),cluster), function(x) f(T%*%t(X)))) but same thing basically. Thanks – Rik Apr 27 '15 at 19:05
  • sorry, you are getting the same results because I had a typo in the code, it was an upper case x in f(x) – Rik Apr 27 '15 at 19:37
  • For some reason this split line gave the same answer, might be a bug but I don't think it is right because when I split X, it gives me vectors. you could trans form the vector into a matrix but there is a missing step, and it turns into a long line – Rik Apr 27 '15 at 20:25
  • david, yes that works. I didn't understand it but I do now thankls – Rik Apr 27 '15 at 20:34