[R-es] optimización de código en R

Olivier Nuñez onunez en unex.es
Vie Ene 18 00:02:34 CET 2013


Tania,

aquí se optimiza vectorizando el bucle (ver The Art of R Programming:  
A Tour of Statistical Software Design de Norman Matloff)

sim3 <- function(nreps)  {
    nb1 <- 10  # 10 blue marbles in Urn 1
    nb2 = 6  # 6 blue marbles orig. in Urn 2
    n1 <- 18  # number of marbles in Urn 1 at 1st pick
    n2 <- 13  # number of marbles in Urn 2 at 2nd pick
    count <- 0  # number of repetitions in which get blue from Urn 2
    u <- matrix(c(runif(2*nreps)),nrow=nreps,ncol=2)
    cndt <- (u[,1] <= nb1/n1) & (u[,2] <= (nb2+1)/n2) | (u[,1] > nb1/ 
n1) & (u[,2] <= nb2/n2)
    return(mean(cndt))  # est. P(pick blue from Urn 2)
}

Un saludo. Olivier

PD: creo que la función que propone Carlos lleva a una estimación  
sesgada.

 > system.time(sim3(100000))
    user  system elapsed
   0.039   0.018   0.058
 > system.time(sim1(100000))
    user  system elapsed
   2.002   0.035   2.034

--  
____________________________________

Olivier G. Nuñez
Email: onunez en unex.es
http://matematicas.unex.es/~onunez
Tel : +34 663 03 69 09
Departamento de Matemáticas
Universidad de Extremadura

____________________________________





El 17/01/2013, a las 20:00, Tania Patiño escribió:

>  nb1 <- 10  # 10 blue marbles in Urn 1
>    n1 <- 18  # number of marbles in Urn 1 at 1st pick
>    n2 <- 13  # number of marbles in Urn 2 at 2nd pick



Más información sobre la lista de distribución R-help-es