Tutorial R

Tubos, funciones, vectores e Iteración

VE-CC

14-11-2021

1 Las pipes (%>%)

Facilitan la comprensión del código. El objetivo de la tubería es escribir código de una manera que sea más fácil de leer y comprender. Son muy poderosas para crear expresiones y secuencias de control que combinan múltiples operaciones sin la necesidad de crear variables intermedias.

library(tidyverse)
library(magrittr)
# foo_foo <- little_bunny()
# hop()
# scoop()
# bop()

con variables intermedias

# foo_foo_1 <- hop(foo_foo, through = forest)
# foo_foo_2 <- scoop(foo_foo_1, up = field_mice)
# foo_foo_3 <- bop(foo_foo_2, on = head)

pryr::object_size entrega el tamano

# dd <- ggplot2::diamonds
# dd1 <- dd %>%
#     dplyr::mutate(price_per_carat = price / carat)
# 
# dd$carat[1] <- NA
# pryr::object_size(dd)
# pryr::object_size(dd1)
# pryr::object_size(dd,dd1)

1.1 Sobreescribimos la variable original

# foo_foo <- hop(foo_foo, through = forest)
# foo_foo <- scoop(foo_foo, up = field_mice)
# foo_foo <- bop(foo_foo, on = head)

Componer funciones

# bop(
#     scoop(
#         hop(
#             foo_foo,
#             through = forest
#         ),
#         up = field_mice),
#     on = head
#     )

usando pipes

# foo_foo %>%
#     hop(through = forest) %>%
#     scoop(up = field_mide) %>%
#     bop(on = head)

funciones

# my_own_pipe <- function(.){
#     . <- hop(., through = forest)
#     . <- scoop(., through = field_mice)
#     . <- bop(., on = head)
#     return(.)
# }

1.2 assign, get y load

# assign("x",3)
# "x" %>% assign(6)
# env <- enviroment()
# "x" %>% assign(6, envir = env)
# x

2 tryCatch, try, supressMessages, supressWarnings

# tryCatch(stop("!"),
#           error = function(e) "error")
# stop("!") %>%
#         tryCatch (error = function(e) "error")

Otra herramientras de Magritr

rnorm(1000) %>%
    matrix(ncol = 2) %T>%
    plot() %>%
    str()

##  num [1:500, 1:2] 1.154 -0.185 -0.331 0.803 -0.458 ...
mtcars %$% cor(disp, mpg)
## [1] -0.8475514

Boomerang: %<>%

mtcars %<>% filter(cyl == 6)

2.1 Creacion de funciones