[R] vectorize a function

Robin Hankin r.hankin at noc.soton.ac.uk
Fri Jun 22 15:28:07 CEST 2007


Hello everyone

suppose I have an integer vector "a" of length "n" and
a symmetric matrix "M" of size n-by-n.

Vector "a" describes a partition of a set of "n" elements
and matrix M describes a penalty function: row i column
j represents the penalty if element i and element j
are in the same partition.

Toy example follows; the real case is much larger
and I need to evaluate my penalty function many times.

If a <- c(1,1,2,1,3)  then elements 1,2,4 are in the
same partition; element 3 is in a partition on its own
and element 5 is in a partition on its own.

The total penalty  can be described by the following (ugly)
function:

f <- function(a,M){
   out <- 0
   for(i in unique(a)){
     out <- out + sum(M[which(a==i),which(a==i)])
   }
   return(out)
}


so with

M <- matrix(rpois(25,3),5,5)
M <- M+t(M)
diag(M) <- 0
a <- c(1,2,1,1,3)

f(a,M) gives the total penalty.


QUESTION:  how to rewrite f() so that it has no loop?






--
Robin Hankin
Uncertainty Analyst
National Oceanography Centre, Southampton
European Way, Southampton SO14 3ZH, UK
  tel  023-8059-7743



More information about the R-help mailing list