[R] vectorize a function

From: Robin Hankin <r.hankin_at_noc.soton.ac.uk>
Date: Fri, 22 Jun 2007 14:28:07 +0100


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

______________________________________________
R-help_at_stat.math.ethz.ch mailing list
https://stat.ethz.ch/mailman/listinfo/r-help
PLEASE do read the posting guide http://www.R-project.org/posting-guide.html
and provide commented, minimal, self-contained, reproducible code.
Received on Fri 22 Jun 2007 - 13:34:40 GMT

Archive maintained by Robert King, hosted by the discipline of statistics at the University of Newcastle, Australia.
Archive generated by hypermail 2.2.0, at Fri 22 Jun 2007 - 18:32:11 GMT.

Mailing list information is available at https://stat.ethz.ch/mailman/listinfo/r-help. Please read the posting guide before posting to the list.