[R] mapply

Dimitris Rizopoulos d.rizopoulos at erasmusmc.nl
Sun May 31 10:01:36 CEST 2009


well, you do not have to compute the pairwise difference each time; for 
instance, you could use something like this (untested):

out1 <- outer(a, c, "-")
out2 <- outer(b, c, "-")

u <- v <- 1:5
mat <- matrix(0, length(u), length(u))
for (i in seq_len(u)) {
     for (j in seq_len(v)) {
         res1 <- colSums(abs(out1 - i) == 0) > 0
         res2 <- colSums(abs(out2 - j) == 0) > 0
         mat[i, j] <- sum(res1 & res2)
     }
}
mat


I hope it helps.

Best,
Dimitris


KARAVASILIS GEORGE wrote:
> Hello, R users.
> I would like to count the number of triples (r_i, s_j, t_k) with r_i, 
> s_j, t_k distinct and abs((r_i-t_k)-u)=0 and abs((s_j-t_k)-v)=0, where 
> r_i, s_j, t_k are the elements of three vectors a,b,c with different 
> lengths and u,v=1:n. I have solved this problem writing a subroutine in 
> Fortran an calling .Fortran(). I would like to find another way to use  
> functions like mapply. I tried this one:
> 
>  xx <- mapply( function(u,v)   {
>  kk <- outer(a, c, function(s,t) abs((s-t)-u)==0)
>  ll <- outer(b, c, function(s,t) abs((s-t)-v)==0)
>  sum( outer( which(kk==TRUE, TRUE)[,2], which(ll==TRUE, TRUE)[,2], 
> function(s,t) s==t)  )  },
>  rep(1:n, each=n), rep(1:n, times=n)    )
> 
>  xx <- matrix(xx, nrow=n, ncol=n, byrow=TRUE)
> 
> It works but it is rather slow. Taking into account that my vectors have 
> lengths 3000, and n is from 50 to 200, can I do something to improve the 
> running  time of the above code?
> 
> ______________________________________________
> R-help at r-project.org 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.
> 

-- 
Dimitris Rizopoulos
Assistant Professor
Department of Biostatistics
Erasmus University Medical Center

Address: PO Box 2040, 3000 CA Rotterdam, the Netherlands
Tel: +31/(0)10/7043478
Fax: +31/(0)10/7043014




More information about the R-help mailing list