13 outubro, 2021
# Vetorização da soma de vetores 1:4 + 10:13
## [1] 11 13 15 17
# Similarmente a representação 1 2 3 4 + + + + 10 11 12 13 ------------ 11 13 15 17
# Se usássemos o loop x <- 1:4 y <- 10:13 for (i in 1:4) { print(x[i] + y[i]) }
## [1] 11 ## [1] 13 ## [1] 15 ## [1] 17
# Funcao logaritmica log(1:4) ## [1] 0.0000000 0.6931472 1.0986123 1.3862944 # Multiplicacao 10:20 * 5 ## [1] 50 55 60 65 70 75 80 85 90 95 100 # Operadores logicos 1 == 1:4 ## [1] TRUE FALSE FALSE FALSE # Gerador de numeros aleatorios [0, 1] runif(1:10) ## [1] 0.2231106 0.8729898 0.7690809 0.7346476 0.3877575 0.6751893 0.3350771 ## [8] 0.5355075 0.3738374 0.9832827
`%soma%` <- function(e1, e2) { e1 + e2 } # Exemplo 1 1:4 %soma% 10:13
## [1] 11 13 15 17
# Exemplo 2 1:4 %soma% 5
## [1] 6 7 8 9
# Semente set.seed(10) # Gerando a amostra rnorm(10, 1:3, 1) ## [1] 1.0187462 1.8157475 1.6286695 0.4008323 2.2945451 3.3897943 ## [7] -0.2080762 1.6363240 1.3733273 0.7435216
# Apos a vetorizacao, observe a diferenca entre # 'rnorm_vet1' e 'rnorm_vet2', devido ao argumento # 'SIMPLIFY' rnorm_vet1 <- Vectorize(rnorm, "mean", SIMPLIFY = FALSE) rnorm_vet2 <- Vectorize(rnorm, "mean", SIMPLIFY = TRUE) # Vetorizando set.seed(10) # semente para fixar os mesmos valores rnorm_vet1(n = 10, mean = 1:3) ## [[1]] ## [1] 1.0187462 0.8157475 -0.3713305 0.4008323 1.2945451 1.3897943 ## [7] -0.2080762 0.6363240 -0.6266727 0.7435216 ## ## [[2]] ## [1] 3.101780 2.755782 1.761766 2.987445 2.741390 2.089347 1.045056 1.804850 ## [9] 2.925521 2.482979 ## ## [[3]] ## [1] 2.4036894 0.8147132 2.3251341 0.8809388 1.7348020 2.6263384 2.3124446 ## [8] 2.1278412 2.8982390 2.7462195
set.seed(10) # semente para fixar os mesmos valores rnorm_vet2(n = 10, mean = 1:3) ## [,1] [,2] [,3] ## [1,] 1.0187462 3.101780 2.4036894 ## [2,] 0.8157475 2.755782 0.8147132 ## [3,] -0.3713305 1.761766 2.3251341 ## [4,] 0.4008323 2.987445 0.8809388 ## [5,] 1.2945451 2.741390 1.7348020 ## [6,] 1.3897943 2.089347 2.6263384 ## [7,] -0.2080762 1.045056 2.3124446 ## [8,] 0.6363240 1.804850 2.1278412 ## [9,] -0.6266727 2.925521 2.8982390 ## [10,] 0.7435216 2.482979 2.7462195