# Re: [R] vectorize a function

From: Christos Hatzis <christos_at_nuverabio.com>
Date: Fri, 22 Jun 2007 10:17:24 -0400

How about:

sum(sapply(unique(a), function(x) {b <- which(a==x); sum(M[b, b])}))

HTH
-Christos

Christos Hatzis, Ph.D.
Nuvera Biosciences, Inc.
400 West Cummings Park
Suite 5350
Woburn, MA 01801
Tel: 781-938-3830
www.nuverabio.com

> -----Original Message-----
> From: r-help-bounces_at_stat.math.ethz.ch
> [mailto:r-help-bounces_at_stat.math.ethz.ch] On Behalf Of Robin Hankin
> Sent: Friday, June 22, 2007 9:28 AM
> To: RHelp help
> Subject: [R] vectorize a function
>
> 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.
>
>

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 - 18:18:09 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 - 19:32:14 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.