Objetivo:

Testar a velocidade da função. Reconstruir função da ultima aula em Rcpp e comparar com as outras usando o microbenchmarking. (usando ifelse, if_else e sample).

Em R

#Função

x.discret.ifelse <- function(n){
  x = runif(n,0,1)
  y2 <- ifelse(x < 0.25, -2, 
               ifelse(x < 0.5,-1, 
                      ifelse(x < 0.75,1,2)))
  return(y2)
}
y <- x.discret.ifelse(1000)
barplot(table(y), col = "lightgreen")

#Função Soma

x.discret.soma <-function(n){
  x <- runif(n,0,1)
  y1 <- -2*(x < 0.25) -1*(x >= 0.25)*(x<0.5) + (x >= 0.5)*(x<0.75) + 2*(x >= 0.75) 
  return(y1)
}

#Utilizando if_else

library("dplyr")
## 
## Attaching package: 'dplyr'
## The following objects are masked from 'package:stats':
## 
##     filter, lag
## The following objects are masked from 'package:base':
## 
##     intersect, setdiff, setequal, union
x.discret.if_else <- function(n){
  x <- runif(n,0,1)
  y3 <- if_else(x < 0.25, -2, 
                if_else(x < 0.5,-1, 
                        if_else(x < 0.75,1,2)))
  return(y3)
}

#sample

x.discret.sample <- function(n){
  x <- c(-2,-1,1,2)
  y4 <- sample(x,replace = T, size = n)
  return(y4)
}

Em RCPP

#Função em Rcpp

#library("Rcpp")
#cppFunction('NumericVector xdiscretifelse(int n) {
#            NumericVector x = runif(n,0,1);
#            NumericVector res(n);
#            for(int i=0; i<n; i++){
#            if(x[i] < 0.25){
#            res[i] = -2;
#            }
#            if(x[i] >= 0.25 && x[i] < 0.5){
#            res[i] = -1;
#            }
#            if(x[i] >= 0.5 && x[i] < 0.75){
#            res[i] = 1;
#            }
#            if(x[i] >= 0.75){
#            res[i] = 2;
#            }
#            }
#            return res;
#            }')


#library("microbenchmark")


#Aplicando o microbenchmarking:

#mc <- microbenchmark(x.discret.soma(1000), x.discret.ifelse(1000),x.discret.if_else(1000),x.discret.sample(1000), xdiscretifelse(1000),  times = 100, control = list(order = "random"))

#mc

Conclusão:

Observando a média e a médiana, a função com menor tempo máximo foi a xdiscretifelse() do Rcpp. A que obteve menor média também foi a função xdiscretifelse(), e com menor mediana x.discret.soma(). Esta também tem menor tempo mínimo. Considerando que a melhor função é a que tem menor tempo máximo, a x.discret.soma() tem o melhor desempenho.