################################################################################ ### TALLER FUNDAMENTOS DE R ### ### PRESENTACIÓN 9: CONTROL DE FLUJO ### ### ### ### Center for Conservation and Sustainable Development ### ### Missouri Botanical Garden ### ### Sitio de la red: rbasicsworkshop.weebly.com ### ################################################################################ ################################################################################ ### 1. BUCLES *while* ########################################################## ################################################################################ # *while* también es muy útil para construir bucles. Este tipo de bucle repite # un pedazo de código mientras una condición determinada es cierta. # La estructura general de un bucle *while* es la siguiente: # # while(condición) # { # código # } # Esto quiere decir aproximadamente: # # mientras esta condición es verdadera repetir # { # este código # } ##################### ## Ejemplo fácil 1 ## ##################### v <- 1:10 # Versión 1 i <- 0 while(i < max(v)) { i <- i+1 print(i) } ##################### ## Ejemplo fácil 2 ## ##################### Bp <- 0.1 Dp <- 0.1 Np <- 1-Bp-Dp max.t <- 100 time <- 0 abund <- 10 plot(c(0, max.t), c(0, 100), type="n") while(abund>0 & time<=max.t) { change <- sample(c(-1,0,1), size=abund, prob=c(Dp, Np, Bp), replace=TRUE) abund <- abund + sum(change) time <- time + 1 points(time, abund, pch=16, col="black") #Sys.sleep(0.2) } ################################################################################ ### 2. CONDICIONAL: *if* ####################################################### ################################################################################ # El condicional *if* permite correr un pedazo de código solamente si una # condición en particular es verdadera ##################### ## Ejemplo fácil 1 ## ##################### v <- 1:10 for(i in v) { print(i) if(i == 5) print("Reached 5") # Con un solo comando, las llaves {} no son necesarias } #################### ## Easy example 2 ## #################### ## THE WHILE DATING LOOP ## you <- runif(1, 0, 100) # Your personality in a number your.pickiness.score <- 0.1 # How closely you want your date # to match your personality missmatch <- Inf # The initial difference in personality date <- 0 # Your date number while(missmatch > your.pickiness.score) { date <- date + 1 they <- runif(1, 0, 100) missmatch <- abs(you - they) if(missmatch <= your.pickiness.score) { print("Congratulations, you are getting married!!") print(paste("You've dated", date, "people", sep=" ")) } } ################################################################################ ### 3. RUPTURAS: *break* ####################################################### ################################################################################ # La función *break* causa que un bucle termine. Se usa frecuentemente en # conjunto con un condicional ##################### ## Ejemplo fácil 1 ## ##################### v <- 1:10 for(i in v) { print(i) if(i == 5) # Con mas de un comando, las llaves {} son necesarias { print("Reached 5") break() } } ################################################################################ ### 4. COMO EVITAR BUCLES ###################################################### ################################################################################ # Los bucles son extremadamente útiles, pero también pueden ser lentos. Cuando # es posible, es buena idea evitar utilizar bucles en R y utilizar funciones # que ya existen en R. A esto se le llama: vectorización. # Por ejemplo, supongamos que tenemos una matriz muy grande de abundancia de # 10 especies en 1,000,000 de sitios M <- matrix(rpois(10000000, 10), ncol=10) dim(M) head(M) # Como calcular la abundancia total de individuos por sitio (fila)? ## Opción 1 - un bucle muy ineficiente ## abund.1 <- numeric() system.time( for(i in 1:nrow(M)) { abund.1 <- c(abund.1, sum(M[i,])) } ) ## Opción 2 - un bucle un poco mejor construido ## abund.2 <- rep(NA, nrow(M)) system.time( for(i in 1:nrow(M)) { abund.2[i] <- sum(M[i,]) } ) ## Opción 4 - vectorización ## system.time( abund.4 <- colSums(M) ) ## ver función *apply* ?apply system.time( abund.5 <- apply(M, 2, sum) )