1. Install and load the packages usingR and MASS.
#Instalamos los paquetes MASS e UsingR
#install.packages("MASS")
#install.packages("UsingR")
#install.packages("e1071")
#install.packages("densityClust")

#Invocamos cada una de las librerias que vamos a necesitar para construir los graficos
library(dplyr)
## 
## Adjuntando el paquete: 'dplyr'
## The following objects are masked from 'package:stats':
## 
##     filter, lag
## The following objects are masked from 'package:base':
## 
##     intersect, setdiff, setequal, union
library(ggplot2)
library(plotly)
## 
## Adjuntando el paquete: 'plotly'
## The following object is masked from 'package:ggplot2':
## 
##     last_plot
## The following object is masked from 'package:stats':
## 
##     filter
## The following object is masked from 'package:graphics':
## 
##     layout
library(MASS)
## 
## Adjuntando el paquete: 'MASS'
## The following object is masked from 'package:plotly':
## 
##     select
## The following object is masked from 'package:dplyr':
## 
##     select
library(UsingR)
## Cargando paquete requerido: HistData
## Cargando paquete requerido: Hmisc
## 
## Adjuntando el paquete: 'Hmisc'
## The following object is masked from 'package:plotly':
## 
##     subplot
## The following objects are masked from 'package:dplyr':
## 
##     src, summarize
## The following objects are masked from 'package:base':
## 
##     format.pval, units
library(e1071)
## 
## Adjuntando el paquete: 'e1071'
## The following object is masked from 'package:Hmisc':
## 
##     impute
library(densityClust)
  1. brightness contain information on the brightness of 966 stars.

a.Represent these data employing a histogram and a superimposed density plot.

#Se carga la base de datos con el metodo data
data(brightness)
#Se consulta la base de datos invocandola por su nombre y saber que datos contiene
#brightness
#Se construye el histograma usando el metodo hist()
histBright <- hist(brightness,
                     main="Brillo de las estrellas",
                     labels = TRUE,
                     xlab = "Brillo",
                     ylab = "Cantidad de estrellas",
                     ylim = c(0,400),
                     xlim = c(0,15),
                     col = "red"
                     )
#Se usa el metodo axis para que el eje x vaya de 1 en 1 hasta el tamaño del eje
axis(1,at=seq(0,15,by=1))

#Se construye el dataset usando el metodo data.frame(), definimos la variable "x" para representar el numero de la estrella y la variable "y" para representar el brillo de cada estrella segun la informacion de la base de datos
dfBrightness <- data.frame(x = 1:length(brightness), y = brightness)

#Construimos el diagrama de densidad usando el dataframe y la propiedad geom_density
densBrPlot <- ggplot(dfBrightness, aes(x = brightness)) +
              geom_density(fill = "lightblue", color = "black") +
              geom_histogram(aes(y = ..density..), bins = 30, fill = "lightgray", color = "black", alpha = 0.5) +
              labs(title = "Grafico de Densidad del Brillo de 966 Estrellas",
              x = "Brillo",
              y = "Densidad") +
              theme_minimal() +
              theme(panel.grid.major = element_line(color = "grey80"),  # Color de las líneas de la cuadrícula principal
                    panel.grid.minor = element_line(color = "grey90"),  # Color de las líneas de la cuadrícula menor
                    panel.border = element_rect(color = "black", fill = NA))
 densBrPlot
## Warning: The dot-dot notation (`..density..`) was deprecated in ggplot2 3.4.0.
## ℹ Please use `after_stat(density)` instead.
## This warning is displayed once every 8 hours.
## Call `lifecycle::last_lifecycle_warnings()` to see where this warning was
## generated.

b. Graphically represent these data using a boxplot.

-Would you say that the data have “outliers”?

Si, en el histograma se aprecian valores atipicos por fuera de los valores maximo y minimo de las estadisticas del brillo de las estrellas.

# Crear el boxplot
mediana <- median(dfBrightness$y)

boxPlotBright <- ggplot(dfBrightness, 
                        aes(x = "", y = brightness)) +
                  geom_boxplot(fill="green",color="black") +
                  stat_summary(fun = median, geom = "point", color = "black", size = 3) +
                  annotate("text", x = 1, y = mediana, label = paste("Promedio:", round(mediana, 2)),
                      color = "black", vjust = 1.5) +
                  labs(title = "Boxplot del Brillo de 966 Estrellas",
                  x = "",
                  y = "Brillo") +
                  theme_gray()
boxPlotBright

-What is the second smallest outlier?

El segundo valor atipico mas lejano es 2.28

# Calcular los valores del boxplot
boxplotStat <- boxplot(dfBrightness$y, plot = FALSE)

# Extraemos los valores atipicos del boxplot
outliersBright <- boxplotStat$out

# Ordenar los valores atipicos de manera ascendente
sortOutliersBright <- sort(outliersBright)

# Imprimir el segundo menor outlier
secondSmallestOutBr <- sortOutliersBright[2]
secondSmallestOutBr
## [1] 2.28
  1. We want to keep data that cannot be considered outliers. Create a new variable called brightness.without containing only the values without outliers.
boxPlotBrSinOut <- ggplot(dfBrightness, 
                        aes(x = "", y = brightness)) +
                        geom_boxplot(fill="green",color="black",outlier.shape = NA) +
                        stat_summary(fun = median, geom = "point", color = "black", size = 3) +
                        annotate("text", x = 1, y = mediana, label = paste("Promedio:", round(mediana, 2)),
                          color = "black", vjust = 1.5) +
                        labs(title = "Boxplot del Brillo de 966 Estrellas",
                            x = "",
                            y = "Brillo") +
                        theme_gray()
boxPlotBrSinOut

Histograma: Muestra la frecuencia de los valores en intervalos específicos.

Gráfico de Densidad: Muestra la densidad de los valores de brillo a lo largo del rango de datos.

# Calcular la asimetría
valorAsimetria <- skewness(dfBrightness$y)
valorAsimetria
## [1] -0.2597829
# Calcular la densidad
densidad <- density(dfBrightness$y)

# Encontrar los picos (modos)
picos <- which(diff(sign(diff(densidad$y))) == -2) + 1

# Mostrar los picos
data.frame(x = densidad$x[picos], y = densidad$y[picos])
##           x           y
## 1  2.174858 0.003099199
## 2  8.579479 0.395861342
## 3 11.677743 0.020291018
  1. UScereal contain information on the breakfast with cereals.
#Se descarga la base de datos
data(UScereal)
#UScereal  
  1. Determine and interpret the relationships between the following pairs of variables using scatter plots, boxplots, or bar charts as appropriate:

I. manufacturer & shelf.

Se observa que los fabricantes G, K y P tienen productos en las tres estanterias, siendo G y K los fabricantes con mayor cantidad de productos en las estanterias. Es decir que tiene mayor participacion u opcion de que un desayuno de una familia americana tenga alguno de sus productos.

# Contar el número de cereales por fabricante
dsCerealCount <- UScereal %>%
                  group_by(mfr, shelf) %>%
                  summarise(n = n())
## `summarise()` has grouped output by 'mfr'. You can override using the `.groups`
## argument.
#dsCerealCount

# Crear el gráfico de barras
barUsCereal <- ggplot(dsCerealCount, aes(x = mfr, y = n)) +
  geom_bar(stat = "identity", fill = "lightblue", color = "black") +
  geom_text(aes(label = n), vjust = -0.5, color = "black") +
  labs(title = "Cantidad de productos por Fabricante",
       x = "Fabricante",
       y = "Cantidad") +
  facet_wrap(~ shelf)
  theme_minimal() +
  theme(axis.text.x = element_text(angle = 0, hjust = 1))
## List of 136
##  $ line                            :List of 6
##   ..$ colour       : chr "black"
##   ..$ linewidth    : num 0.5
##   ..$ linetype     : num 1
##   ..$ lineend      : chr "butt"
##   ..$ arrow        : logi FALSE
##   ..$ inherit.blank: logi TRUE
##   ..- attr(*, "class")= chr [1:2] "element_line" "element"
##  $ rect                            :List of 5
##   ..$ fill         : chr "white"
##   ..$ colour       : chr "black"
##   ..$ linewidth    : num 0.5
##   ..$ linetype     : num 1
##   ..$ inherit.blank: logi TRUE
##   ..- attr(*, "class")= chr [1:2] "element_rect" "element"
##  $ text                            :List of 11
##   ..$ family       : chr ""
##   ..$ face         : chr "plain"
##   ..$ colour       : chr "black"
##   ..$ size         : num 11
##   ..$ hjust        : num 0.5
##   ..$ vjust        : num 0.5
##   ..$ angle        : num 0
##   ..$ lineheight   : num 0.9
##   ..$ margin       : 'margin' num [1:4] 0points 0points 0points 0points
##   .. ..- attr(*, "unit")= int 8
##   ..$ debug        : logi FALSE
##   ..$ inherit.blank: logi TRUE
##   ..- attr(*, "class")= chr [1:2] "element_text" "element"
##  $ title                           : NULL
##  $ aspect.ratio                    : NULL
##  $ axis.title                      : NULL
##  $ axis.title.x                    :List of 11
##   ..$ family       : NULL
##   ..$ face         : NULL
##   ..$ colour       : NULL
##   ..$ size         : NULL
##   ..$ hjust        : NULL
##   ..$ vjust        : num 1
##   ..$ angle        : NULL
##   ..$ lineheight   : NULL
##   ..$ margin       : 'margin' num [1:4] 2.75points 0points 0points 0points
##   .. ..- attr(*, "unit")= int 8
##   ..$ debug        : NULL
##   ..$ inherit.blank: logi TRUE
##   ..- attr(*, "class")= chr [1:2] "element_text" "element"
##  $ axis.title.x.top                :List of 11
##   ..$ family       : NULL
##   ..$ face         : NULL
##   ..$ colour       : NULL
##   ..$ size         : NULL
##   ..$ hjust        : NULL
##   ..$ vjust        : num 0
##   ..$ angle        : NULL
##   ..$ lineheight   : NULL
##   ..$ margin       : 'margin' num [1:4] 0points 0points 2.75points 0points
##   .. ..- attr(*, "unit")= int 8
##   ..$ debug        : NULL
##   ..$ inherit.blank: logi TRUE
##   ..- attr(*, "class")= chr [1:2] "element_text" "element"
##  $ axis.title.x.bottom             : NULL
##  $ axis.title.y                    :List of 11
##   ..$ family       : NULL
##   ..$ face         : NULL
##   ..$ colour       : NULL
##   ..$ size         : NULL
##   ..$ hjust        : NULL
##   ..$ vjust        : num 1
##   ..$ angle        : num 90
##   ..$ lineheight   : NULL
##   ..$ margin       : 'margin' num [1:4] 0points 2.75points 0points 0points
##   .. ..- attr(*, "unit")= int 8
##   ..$ debug        : NULL
##   ..$ inherit.blank: logi TRUE
##   ..- attr(*, "class")= chr [1:2] "element_text" "element"
##  $ axis.title.y.left               : NULL
##  $ axis.title.y.right              :List of 11
##   ..$ family       : NULL
##   ..$ face         : NULL
##   ..$ colour       : NULL
##   ..$ size         : NULL
##   ..$ hjust        : NULL
##   ..$ vjust        : num 1
##   ..$ angle        : num -90
##   ..$ lineheight   : NULL
##   ..$ margin       : 'margin' num [1:4] 0points 0points 0points 2.75points
##   .. ..- attr(*, "unit")= int 8
##   ..$ debug        : NULL
##   ..$ inherit.blank: logi TRUE
##   ..- attr(*, "class")= chr [1:2] "element_text" "element"
##  $ axis.text                       :List of 11
##   ..$ family       : NULL
##   ..$ face         : NULL
##   ..$ colour       : chr "grey30"
##   ..$ size         : 'rel' num 0.8
##   ..$ hjust        : NULL
##   ..$ vjust        : NULL
##   ..$ angle        : NULL
##   ..$ lineheight   : NULL
##   ..$ margin       : NULL
##   ..$ debug        : NULL
##   ..$ inherit.blank: logi TRUE
##   ..- attr(*, "class")= chr [1:2] "element_text" "element"
##  $ axis.text.x                     :List of 11
##   ..$ family       : NULL
##   ..$ face         : NULL
##   ..$ colour       : NULL
##   ..$ size         : NULL
##   ..$ hjust        : num 1
##   ..$ vjust        : num 1
##   ..$ angle        : num 0
##   ..$ lineheight   : NULL
##   ..$ margin       : 'margin' num [1:4] 2.2points 0points 0points 0points
##   .. ..- attr(*, "unit")= int 8
##   ..$ debug        : NULL
##   ..$ inherit.blank: logi FALSE
##   ..- attr(*, "class")= chr [1:2] "element_text" "element"
##  $ axis.text.x.top                 :List of 11
##   ..$ family       : NULL
##   ..$ face         : NULL
##   ..$ colour       : NULL
##   ..$ size         : NULL
##   ..$ hjust        : NULL
##   ..$ vjust        : num 0
##   ..$ angle        : NULL
##   ..$ lineheight   : NULL
##   ..$ margin       : 'margin' num [1:4] 0points 0points 2.2points 0points
##   .. ..- attr(*, "unit")= int 8
##   ..$ debug        : NULL
##   ..$ inherit.blank: logi TRUE
##   ..- attr(*, "class")= chr [1:2] "element_text" "element"
##  $ axis.text.x.bottom              : NULL
##  $ axis.text.y                     :List of 11
##   ..$ family       : NULL
##   ..$ face         : NULL
##   ..$ colour       : NULL
##   ..$ size         : NULL
##   ..$ hjust        : num 1
##   ..$ vjust        : NULL
##   ..$ angle        : NULL
##   ..$ lineheight   : NULL
##   ..$ margin       : 'margin' num [1:4] 0points 2.2points 0points 0points
##   .. ..- attr(*, "unit")= int 8
##   ..$ debug        : NULL
##   ..$ inherit.blank: logi TRUE
##   ..- attr(*, "class")= chr [1:2] "element_text" "element"
##  $ axis.text.y.left                : NULL
##  $ axis.text.y.right               :List of 11
##   ..$ family       : NULL
##   ..$ face         : NULL
##   ..$ colour       : NULL
##   ..$ size         : NULL
##   ..$ hjust        : num 0
##   ..$ vjust        : NULL
##   ..$ angle        : NULL
##   ..$ lineheight   : NULL
##   ..$ margin       : 'margin' num [1:4] 0points 0points 0points 2.2points
##   .. ..- attr(*, "unit")= int 8
##   ..$ debug        : NULL
##   ..$ inherit.blank: logi TRUE
##   ..- attr(*, "class")= chr [1:2] "element_text" "element"
##  $ axis.text.theta                 : NULL
##  $ axis.text.r                     :List of 11
##   ..$ family       : NULL
##   ..$ face         : NULL
##   ..$ colour       : NULL
##   ..$ size         : NULL
##   ..$ hjust        : num 0.5
##   ..$ vjust        : NULL
##   ..$ angle        : NULL
##   ..$ lineheight   : NULL
##   ..$ margin       : 'margin' num [1:4] 0points 2.2points 0points 2.2points
##   .. ..- attr(*, "unit")= int 8
##   ..$ debug        : NULL
##   ..$ inherit.blank: logi TRUE
##   ..- attr(*, "class")= chr [1:2] "element_text" "element"
##  $ axis.ticks                      : list()
##   ..- attr(*, "class")= chr [1:2] "element_blank" "element"
##  $ axis.ticks.x                    : NULL
##  $ axis.ticks.x.top                : NULL
##  $ axis.ticks.x.bottom             : NULL
##  $ axis.ticks.y                    : NULL
##  $ axis.ticks.y.left               : NULL
##  $ axis.ticks.y.right              : NULL
##  $ axis.ticks.theta                : NULL
##  $ axis.ticks.r                    : NULL
##  $ axis.minor.ticks.x.top          : NULL
##  $ axis.minor.ticks.x.bottom       : NULL
##  $ axis.minor.ticks.y.left         : NULL
##  $ axis.minor.ticks.y.right        : NULL
##  $ axis.minor.ticks.theta          : NULL
##  $ axis.minor.ticks.r              : NULL
##  $ axis.ticks.length               : 'simpleUnit' num 2.75points
##   ..- attr(*, "unit")= int 8
##  $ axis.ticks.length.x             : NULL
##  $ axis.ticks.length.x.top         : NULL
##  $ axis.ticks.length.x.bottom      : NULL
##  $ axis.ticks.length.y             : NULL
##  $ axis.ticks.length.y.left        : NULL
##  $ axis.ticks.length.y.right       : NULL
##  $ axis.ticks.length.theta         : NULL
##  $ axis.ticks.length.r             : NULL
##  $ axis.minor.ticks.length         : 'rel' num 0.75
##  $ axis.minor.ticks.length.x       : NULL
##  $ axis.minor.ticks.length.x.top   : NULL
##  $ axis.minor.ticks.length.x.bottom: NULL
##  $ axis.minor.ticks.length.y       : NULL
##  $ axis.minor.ticks.length.y.left  : NULL
##  $ axis.minor.ticks.length.y.right : NULL
##  $ axis.minor.ticks.length.theta   : NULL
##  $ axis.minor.ticks.length.r       : NULL
##  $ axis.line                       : list()
##   ..- attr(*, "class")= chr [1:2] "element_blank" "element"
##  $ axis.line.x                     : NULL
##  $ axis.line.x.top                 : NULL
##  $ axis.line.x.bottom              : NULL
##  $ axis.line.y                     : NULL
##  $ axis.line.y.left                : NULL
##  $ axis.line.y.right               : NULL
##  $ axis.line.theta                 : NULL
##  $ axis.line.r                     : NULL
##  $ legend.background               : list()
##   ..- attr(*, "class")= chr [1:2] "element_blank" "element"
##  $ legend.margin                   : 'margin' num [1:4] 5.5points 5.5points 5.5points 5.5points
##   ..- attr(*, "unit")= int 8
##  $ legend.spacing                  : 'simpleUnit' num 11points
##   ..- attr(*, "unit")= int 8
##  $ legend.spacing.x                : NULL
##  $ legend.spacing.y                : NULL
##  $ legend.key                      : list()
##   ..- attr(*, "class")= chr [1:2] "element_blank" "element"
##  $ legend.key.size                 : 'simpleUnit' num 1.2lines
##   ..- attr(*, "unit")= int 3
##  $ legend.key.height               : NULL
##  $ legend.key.width                : NULL
##  $ legend.key.spacing              : 'simpleUnit' num 5.5points
##   ..- attr(*, "unit")= int 8
##  $ legend.key.spacing.x            : NULL
##  $ legend.key.spacing.y            : NULL
##  $ legend.frame                    : NULL
##  $ legend.ticks                    : NULL
##  $ legend.ticks.length             : 'rel' num 0.2
##  $ legend.axis.line                : NULL
##  $ legend.text                     :List of 11
##   ..$ family       : NULL
##   ..$ face         : NULL
##   ..$ colour       : NULL
##   ..$ size         : 'rel' num 0.8
##   ..$ hjust        : NULL
##   ..$ vjust        : NULL
##   ..$ angle        : NULL
##   ..$ lineheight   : NULL
##   ..$ margin       : NULL
##   ..$ debug        : NULL
##   ..$ inherit.blank: logi TRUE
##   ..- attr(*, "class")= chr [1:2] "element_text" "element"
##  $ legend.text.position            : NULL
##  $ legend.title                    :List of 11
##   ..$ family       : NULL
##   ..$ face         : NULL
##   ..$ colour       : NULL
##   ..$ size         : NULL
##   ..$ hjust        : num 0
##   ..$ vjust        : NULL
##   ..$ angle        : NULL
##   ..$ lineheight   : NULL
##   ..$ margin       : NULL
##   ..$ debug        : NULL
##   ..$ inherit.blank: logi TRUE
##   ..- attr(*, "class")= chr [1:2] "element_text" "element"
##  $ legend.title.position           : NULL
##  $ legend.position                 : chr "right"
##  $ legend.position.inside          : NULL
##  $ legend.direction                : NULL
##  $ legend.byrow                    : NULL
##  $ legend.justification            : chr "center"
##  $ legend.justification.top        : NULL
##  $ legend.justification.bottom     : NULL
##  $ legend.justification.left       : NULL
##  $ legend.justification.right      : NULL
##  $ legend.justification.inside     : NULL
##  $ legend.location                 : NULL
##  $ legend.box                      : NULL
##  $ legend.box.just                 : NULL
##  $ legend.box.margin               : 'margin' num [1:4] 0cm 0cm 0cm 0cm
##   ..- attr(*, "unit")= int 1
##  $ legend.box.background           : list()
##   ..- attr(*, "class")= chr [1:2] "element_blank" "element"
##  $ legend.box.spacing              : 'simpleUnit' num 11points
##   ..- attr(*, "unit")= int 8
##   [list output truncated]
##  - attr(*, "class")= chr [1:2] "theme" "gg"
##  - attr(*, "complete")= logi TRUE
##  - attr(*, "validate")= logi TRUE
  barUsCereal

  1. fat & vitamins

Podemos observar que los productos con 100 % y enriquecidos de vitaminas contienen ciertos porcentajes de grasas, pero aquellos que estan enriquecidos son los que contienen una mayor concentracion de grasas, inclusive podiamos indicar que la gran mayoria de productos enriquecidos con vitaminas estan por encima del promedio del porcentaje de grasas de todos los productos, condicion que no los hace muy saludables.

#Se calcula el promedio del valor de las grasas de todos los productos
promedioGrasas <- mean(UScereal$fat)

dfUScereal <- data.frame(UScereal)

#Se crea el grafico grasas vs vitaminas
graficoGrasaVitaminas <- ggplot(dfUScereal, aes(x = as.factor(vitamins), y = fat)) +
                                geom_boxplot() +
                                  geom_hline(yintercept = promedioGrasas, color = "red", size = 1) +
                                labs(title = "Grasa vs Vitaminas", x = "Vitaminas", y = "% Grasas") +
                                theme_bw() +
                                theme(plot.title = element_text(hjust = 0.5))
## Warning: Using `size` aesthetic for lines was deprecated in ggplot2 3.4.0.
## ℹ Please use `linewidth` instead.
## This warning is displayed once every 8 hours.
## Call `lifecycle::last_lifecycle_warnings()` to see where this warning was
## generated.
#Convertimos el grafico en interactivo
graVitGrasInter <- ggplotly(graficoGrasaVitaminas)
graVitGrasInter
  1. fat & shelf.
grgraest <- ggplot(dfUScereal, aes(x = as.factor(shelf), y = fat)) +
  geom_boxplot() +
  geom_hline(yintercept = promedioGrasas, color = "red", size = 1) +
  labs(title = "Grasa vs Estante", x = "Estante", y = "% Grasas") +
  theme_bw() +
  theme(plot.title = element_text(hjust = 0.5))
grgraestinteract<-ggplotly(grgraest)
grgraestinteract
  1. carbohydrates & sugars
  carbsug<-ggplot(dfUScereal, aes(x = carbo, y = sugars)) +
  geom_point() +
  labs(title = "Relación entre Carbohidratos y Azúcares", x = "Carbohidratos", y = "Azúcares") +
theme_bw() +
  theme(plot.title = element_text(hjust = 0.5))
carbsuginterac<-ggplotly(carbsug)
carbsuginterac

V. fibre & manufacturer.

promedioFibra <- mean(UScereal$fibre)

boxplotFibra <- ggplot(dfUScereal, aes(x = as.factor(mfr), y = fibre, fill = as.factor(mfr))) +
  geom_boxplot() +
  geom_hline(yintercept = promedioFibra, color = "red", size = 1) +
  labs(title = "Relación entre Fibra y Fabricante", x = "Fabricante", y = "Fibra") +
  theme_bw() +
  theme(plot.title = element_text(hjust = 0.5),
        legend.position = "none")

boxplotFibraInter <- ggplotly(boxplotFibra)
boxplotFibraInter
  1. sodium & sugars.
smoothPlot <- ggplot(dfUScereal, aes(x = sodium, y = sugars)) +
  geom_point(aes(color = sodium), alpha = 0.7) +
  geom_smooth(method = "lm", color = "blue") +
  labs(title = "Relación entre Sodio y Azúcares con Suavizado", x = "Sodio", y = "Azúcares") +
  theme_bw() +
  theme(plot.title = element_text(hjust = 0.5))

smoothPlot
## `geom_smooth()` using formula = 'y ~ x'

smoothPlotInter <- ggplotly(smoothPlot)
## `geom_smooth()` using formula = 'y ~ x'
smoothPlotInter
  1. mammals contain information on relationship between body weight and brain weight of mammals.
  1. Plot the data to visualize the relationship.
data("mammals")
#mammals

grMammals <- ggplot(mammals, aes(x = body, y = brain)) +
  geom_point() +
  geom_smooth(method = "lm", se = FALSE, color = "blue") +
  labs(title = "Relación entre peso cerebro y peso cuerpo", x = "Peso Cuerpo", y = "Peso Cerebro") +
  theme_bw() +
  theme(plot.title = element_text(hjust = 0.5))
grMammalsInt <- ggplotly(grMammals)
## `geom_smooth()` using formula = 'y ~ x'
grMammalsInt
  1. Is there a linear correlation between these variables?

Interpretación: Coeficiente de correlación cercano a 1: Indica una fuerte correlación lineal positiva.

Coeficiente de correlación cercano a -1: Indica una fuerte correlación lineal negativa.

Coeficiente de correlación cercano a 0: Indica que no hay una correlación lineal significativa.

Para nuestro caso si existe una correlacion lineal positiva, dado que su correlacion es cercana a 1. Es decir que la funcion es lineal.

correlacionLineal <- cor(mammals$body, mammals$brain)
correlacionLineal
## [1] 0.9341638
  1. Transform the data using the log function and repeat the study. How do the results change?
logBody <- log(mammals$body)
logBrain <- log(mammals$brain)

grMammalsLog <- ggplot(mammals, aes(x = logBody, y = logBrain)) +
  geom_point() +
  geom_smooth(method = "lm", se = FALSE, color = "blue") +
  labs(title = "Relación entre peso cerebro y peso cuerpo", x = "Peso Cuerpo", y = "Peso Cerebro") +
  theme_bw() +
  theme(plot.title = element_text(hjust = 0.5)) 

grMammalsLogInt <- ggplotly(grMammalsLog)
## `geom_smooth()` using formula = 'y ~ x'
grMammalsLogInt
  1. Anorexia contain information on weight change in female patients.
  1. What treatment was most effective?
data("anorexia")
#anorexia

#Se calcula el cambio de peso
anorexia$weight_change <- anorexia$Postwt - anorexia$Prewt

#Se agrupan los datos por tratamiento y calcular la media del cambio de peso
promedioCambio <- aggregate(weight_change ~ Treat, data = anorexia, FUN = mean)

grAnorexia <- ggplot(anorexia, aes(x = Treat, y = weight_change, fill = Treat)) +
  geom_boxplot()
  labs(title = "Cambio de peso por tratamiento", x = "Tratamiento", y = "Cambio de Peso") +
  theme_bw() +
  theme(plot.title = element_text(hjust = 0.5)) 
## NULL
  grAnorexiaInt <- ggplotly(grAnorexia)
grAnorexiaInt
  1. Contar cuántos pacientes ganaron y cuántos perdieron peso

Pacientes que ganaron peso -> 42 Pacientes que perdieron peso -> 29

ganaronPeso <- sum(anorexia$weight_change > 0)
perdieronPeso <- sum(anorexia$weight_change < 0)
ganaronPeso
## [1] 42
perdieronPeso
## [1] 29