title: "Desarrollo ejecicio Data Analysis Workshop"
author: "ingrid castaño"
date: "2024-08-11"
output: html_document
#install.packages("plotly")
#install.packages("UsingR")
#install.packages("MASS")

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(dslabs)
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(UsingR)
## Cargando paquete requerido: MASS
## 
## Adjuntando el paquete: 'MASS'
## The following object is masked from 'package:plotly':
## 
##     select
## The following object is masked from 'package:dplyr':
## 
##     select
## 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(MASS)
library(readr)

data("brightness")
head(brightness)
## [1]  9.10  9.27  6.61  8.06  8.55 12.31
# A
#install.packages("moments")
library(moments)

brightness_df <- data.frame(brightness)
#head(brightness_df)

# Histograma 

ggplot(data=brightness_df,aes(x=brightness,freq =FALSE))+
  geom_histogram(aes(y = ..density..),bins = 30,binwidth = 0.5, fill = "skyblue", color = "black", alpha = 0.5)+
  geom_density(color = "blue", size = 1,alpha = 0.2) +
  labs(
   title="Histograma de brightness",
   x="brightness",
   y="Frecuencia"
  )+
  theme_light(base_size = 15) + 
  theme(
    plot.title = element_text(hjust = 0.5),  
    axis.title = element_text(face = "bold")   
  )
## 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.
## 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.

# modos
asimetria<- skewness(brightness_df$brightness)
print(paste("Asimetría:", asimetria))
## [1] "Asimetría: -0.260186782151443"
# B
# Crear el diagrama de caja

ggplot(data = brightness_df, aes(y = brightness)) +
  geom_boxplot(fill = "skyblue", color = "black") +
    labs(
    title = "Diagrama de Caja de Brightness",
    x = "",
    y = "Brightness"
  ) +
  theme_classic(base_size = 15) +
  theme(
    plot.title = element_text(hjust = 0.5),
    axis.title = element_text(face = "bold"),
    axis.text.x = element_blank()
  )

## valores atipicos

boxplot_atipi <- boxplot.stats(brightness_df$brightness)
valores_atipicos <- boxplot_atipi$out
valores_atipicos
##  [1] 12.31 11.71  5.53 11.28  4.78  5.13  4.37  5.04 12.43 12.04  4.55 11.55
## [13] 12.14 11.63  4.99 11.67  4.61 11.99 12.04  5.55 12.17 11.55 11.79 12.19
## [25]  2.07 11.65 11.73  2.28  5.42  3.88  5.54  5.29  5.01 11.55  4.89 11.80
## [37]  5.41  5.24
# Segundo valor atipico mas pequeño

segundo_atipico <- sort(valores_atipicos)[2]

print(paste("el segundo atipico es:",segundo_atipico))
## [1] "el segundo atipico es: 2.28"
# quitar los valores atipicos 
brightness_without <- brightness_df[!brightness_df$brightness %in% valores_atipicos,]

# Display the new variable
brightness_without
##   [1]  9.10  9.27  6.61  8.06  8.55  9.64  9.05  8.59  8.59  7.34  8.43  8.80
##  [13]  7.25  8.60  8.15 11.03  6.53  8.51  7.55  8.69  7.57  9.05  6.28  9.13
##  [25]  9.32  8.83  9.14  8.26  7.63  9.09  8.10  6.43  9.07  7.68 10.44  8.65
##  [37]  7.46  8.70 10.61  8.20  6.18  7.91  9.59  8.57 10.78  7.31  9.53  6.49
##  [49]  8.94  8.56 10.96 10.57  7.40  8.12  8.27  7.05  9.09  8.34  8.86  8.27
##  [61]  6.36  8.08 11.00  8.55  7.83  8.79  8.33 10.42  8.26  8.97  6.90  9.93
##  [73]  7.42  9.03  8.41  8.06  8.69  8.40  8.57  9.50  8.85  9.61 10.62  8.05
##  [85]  7.80  5.71  7.87  7.64  7.66  8.68  8.12 10.10  8.67 10.46  9.87  9.48
##  [97]  7.04  8.44  9.88  7.05  8.29  9.34  7.73  6.22  8.53  7.23  8.61 10.76
## [109]  8.93  7.95  7.46  8.60  8.55  9.20  6.82  8.29  6.83  7.21  5.58  8.70
## [121]  8.06 10.86  6.50  9.32  9.14  8.13 10.62  6.62  9.96  8.64  6.60  6.25
## [133]  7.83 10.03  9.04  8.47  7.33  8.66 10.35  8.96  8.49 11.26  8.15  7.04
## [145] 10.02  8.90  7.78  9.93  8.60  8.51  7.09  6.93  8.68  8.98  9.84  8.98
## [157]  7.98 10.16  8.86  8.58  9.56  9.24  9.63  5.80  9.05  8.45  8.86  7.84
## [169]  8.86  8.93  7.97  6.90  8.47  6.77  8.55  8.48  8.53  6.33  8.99  8.64
## [181]  9.55  8.74  8.16  9.46  5.70  7.62  8.95  8.97  8.94  7.24 10.32  8.24
## [193]  8.62  9.18  8.53  8.54  8.56  9.41  5.87  7.20  9.05  9.52 10.24  7.70
## [205]  8.17  7.29  9.26  7.94  8.42  8.56  7.52  7.74  8.85  9.01  7.17  9.04
## [217] 10.30  9.86  7.64  8.27  8.44  9.58  8.43  8.49  9.64  9.17  8.09  9.00
## [229]  6.25  8.56 10.81  8.76  7.76  7.82  7.90  8.52  9.73  9.19  8.10  8.75
## [241]  8.14  8.65 10.30  6.46  6.73  7.96  9.53  8.87  6.59  8.65  9.64  9.15
## [253]  9.04  8.42  8.09  9.06  8.09  8.18  8.77  7.36  9.16  8.82 11.14  6.24
## [265]  9.44  7.49  6.96  7.94  8.69  8.15  8.45  7.92  7.45  9.01  8.55  9.23
## [277]  9.16  7.90  8.68  7.78  8.21  8.11  8.29  7.89  9.67  8.24  6.80  8.18
## [289]  8.44  7.45  6.31  8.15  8.27  7.66  8.59  7.09  8.54  9.58  8.44  8.59
## [301]  8.01  8.29  9.62  7.26  7.91  9.45  8.19  8.93  7.65  8.53  7.38  8.56
## [313]  8.76  9.56  7.09  9.83  5.90 10.80  8.41  9.05  8.79  8.88  7.59  9.60
## [325] 10.66  8.55  8.11  9.44  9.60  5.78 10.66  6.38  8.80  7.79  8.60  7.77
## [337] 10.37  9.80 10.42  9.22  8.43  7.33  8.93  9.09  9.26  8.73  9.18  8.12
## [349]  9.26  8.94  6.11  9.13  7.90  9.34  7.13 10.82  7.46  8.72  7.02  9.08
## [361]  8.37  5.59  7.37  5.68  8.56  8.72  9.06  8.82  8.18  9.39  9.10  8.46
## [373]  9.15  8.28  8.18  7.93  9.21  6.09  8.31  7.83  8.72  6.61  6.25  7.82
## [385]  8.66  8.15  8.97  8.15  7.47  8.63  8.13  8.23  8.41  6.47  9.83  8.64
## [397]  7.73  8.64  8.94  8.84  6.32  5.80  8.97  7.53  7.41  7.80  8.14  6.71
## [409]  8.73  9.37  8.69  9.95  7.10  8.09  6.88  9.48  9.04  9.30  8.49  8.30
## [421]  7.95  7.08  6.93  8.38  8.56  8.78  7.42  8.26  7.71  6.91  9.16  8.99
## [433]  8.63  9.90  7.59  7.39  7.78  7.47  6.97  8.82  9.13  7.86  7.13  9.45
## [445]  8.78  7.23  9.73  7.36  7.36  8.47  9.37  6.99  8.20  8.36  8.22  9.91
## [457]  9.67  8.60 10.07 10.15  7.75  9.21  9.66  8.47  9.37  9.44  9.99 10.38
## [469]  7.51  8.91  7.45  9.57  8.99  8.58  6.90  7.55  7.93  9.71  9.57  8.55
## [481]  6.62  7.89  7.51  7.36  8.66  8.51  6.65  9.67  7.80  8.21  7.90  8.94
## [493]  9.82  8.69  8.57  8.89  5.98  7.92  7.60  8.22  5.70  8.75  6.93  7.97
## [505]  8.06 10.13  7.31  8.35  5.57  9.85  9.16  9.03 10.07  9.76  9.35 10.95
## [517]  8.87  6.68  9.69  8.05 10.30  6.07  8.51  7.71  8.56  8.26  8.62 10.92
## [529] 10.51  9.83  9.84  9.74  8.21  8.72  8.03  9.00  6.19  8.22  7.93 10.18
## [541]  8.98  9.13  6.91  8.79  8.23 10.24  8.83  7.62  8.96 10.41  8.97  9.61
## [553]  8.29  8.30  8.26  7.44  9.52  8.20  8.68  8.65 10.52  8.41  9.18  8.42
## [565]  8.86  7.92 10.97  8.85  9.31 10.28  7.56  7.88  7.99  8.23  8.52  9.14
## [577]  6.20  7.64  8.95  7.48  7.06  7.33  8.98  8.24  8.53  8.40  7.48  8.46
## [589]  9.29  8.57  8.70  8.50  8.37  6.87  7.50  7.39  8.19  7.56  8.37  7.39
## [601]  6.73  8.66  8.25  8.47  8.01  6.83  9.06  8.79  7.44  6.43  5.93  8.85
## [613]  9.86  8.55  7.66  7.82  9.08 10.10  8.21  8.85  7.79  7.58  7.85  7.18
## [625]  7.54  9.72  7.12  9.77  8.84  5.67  8.15  9.61  8.19  7.27  8.51  8.36
## [637] 10.00  8.74  6.18 10.26 10.16  8.31  8.58  7.04  8.81  5.99  8.22  9.86
## [649]  8.00  9.40  9.10  8.11  8.89  9.43  7.59  8.72  9.86  9.23  9.50 10.73
## [661]  7.59  7.41  9.26  7.78  7.76  8.94  8.95  6.41  6.11  7.76  7.38  6.21
## [673]  7.05  7.44  8.50  7.84 11.01  7.88  9.10  8.65  8.41  7.81  7.43  8.76
## [685]  7.58  9.55  6.82 10.24  6.24  7.31 10.52  9.27  7.13  9.14  8.48  8.57
## [697]  7.21  9.05  7.72  8.03  6.47  5.57  6.32  7.78  8.58 10.37  9.23  9.20
## [709]  6.93  9.32  7.11  9.79  8.21  8.42  7.05  9.26  8.77  9.25  9.30 10.63
## [721]  9.90  9.89  9.33  7.78  7.02 11.26  8.89  9.60  7.07  6.01  9.11  8.24
## [733]  8.97  8.59  7.17  7.94  7.27  9.59  7.94  8.52  7.59  9.17  8.08  9.80
## [745]  8.92  9.91  9.42  8.84 10.15  8.37  9.33  9.35  7.40  8.35  9.53  9.59
## [757] 10.05  8.57  8.48  8.43  8.45  8.84 11.18  8.64  8.42  6.34  7.93  8.36
## [769]  8.32  7.77  6.84  8.78  7.19  8.50  8.82  9.04  7.93  7.66 10.07  9.03
## [781]  8.13  7.51  9.08  7.10  7.88  9.40  9.06  8.38 10.65  7.77  8.50  8.61
## [793] 10.05  8.71  9.37  6.97  8.56  9.34  9.47  8.11  8.91  7.83  8.95  7.20
## [805]  9.37  5.84  9.81  9.27  9.50  9.32  8.92  8.38  7.74  8.60  9.49  8.35
## [817]  7.11  9.87  8.98  7.75  8.24  6.74  6.83  7.70  6.70  8.67  9.94  8.73
## [829]  9.63  6.66  8.29  8.47  8.16  8.97  7.51  8.97  8.55  5.84  7.85  8.68
## [841]  8.05  8.27  7.68  9.40  7.77  6.89  7.55  8.27  8.16  8.07  7.91  7.71
## [853] 10.16  8.41  8.88  9.64  7.93  7.78  8.90  8.55  9.15 10.86  9.08  7.44
## [865] 10.35  6.68  8.85  8.90  8.24  6.74 10.75  8.44  7.69  8.88  7.70  8.60
## [877]  8.44  9.50  9.03  7.15  7.95  8.23  9.81  8.48  9.33  8.97  8.08  7.47
## [889]  8.34  7.75  8.34  7.56  6.93 10.03  8.69  9.04  8.32  7.85  7.21  8.98
## [901]  7.09  8.85  9.21  8.61  7.91  7.47  8.65  8.53  9.92  8.09  7.06  8.45
## [913]  8.73  7.45  9.02  7.51  7.32  8.17  9.45  9.72  9.34  8.75  9.32  7.91
## [925]  7.49  6.53  6.18  8.69
# Calcular media
media <- mean(brightness_df$brightness)
print(paste("Media:", media))
## [1] "Media: 8.41774327122153"
## diagrama de caja sin valores atipicos 
ggplot(data = brightness_df, aes(y = brightness)) +
  geom_boxplot(fill = "skyblue", color = "black",outlier.shape = NA) +  # Hide outliers
  geom_hline(yintercept = media, color = "red", linetype =    "dashed")+
   labs(
    title = "Diagrama de Caja de Brightness",
    x = "",
    y = "Brightness"
  ) +
  theme_classic(base_size = 15) +
  theme(
    plot.title = element_text(hjust = 0.5),
    axis.title = element_text(face = "bold"),
    axis.text.x = element_blank()
  )+
  annotate("text", x = 1, y = media, label = paste("Media =", round(media,2)), color = "red")

# 2.UScereal 

data("UScereal")

str(UScereal)
## 'data.frame':    65 obs. of  11 variables:
##  $ mfr      : Factor w/ 6 levels "G","K","N","P",..: 3 2 2 1 2 1 6 4 5 1 ...
##  $ calories : num  212 212 100 147 110 ...
##  $ protein  : num  12.12 12.12 8 2.67 2 ...
##  $ fat      : num  3.03 3.03 0 2.67 0 ...
##  $ sodium   : num  394 788 280 240 125 ...
##  $ fibre    : num  30.3 27.3 28 2 1 ...
##  $ carbo    : num  15.2 21.2 16 14 11 ...
##  $ sugars   : num  18.2 15.2 0 13.3 14 ...
##  $ shelf    : int  3 3 3 1 2 3 1 3 2 1 ...
##  $ potassium: num  848.5 969.7 660 93.3 30 ...
##  $ vitamins : Factor w/ 3 levels "100%","enriched",..: 2 2 2 2 2 2 2 2 2 2 ...
# 2.UScereal 

datos_agrupados<- UScereal%>%
  group_by(mfr) %>%
  summarise(almacenamiento_total= sum(shelf))%>%
  mutate(porcentaje = (almacenamiento_total/sum(almacenamiento_total))*100)


ggplot(data=datos_agrupados,aes(x=mfr,y=porcentaje,fill = mfr))+
  geom_col()+
  geom_text(aes(label=sprintf("%.1f%%", porcentaje)),vjust=1,colour="black")+
  scale_x_discrete(limits = c("K","G","P","Q","R","N"))+
  theme()+
  labs(
    title="Distribucion de cereales por fabricante",
    x="fabricante",
    y="almacenamiento")+
  theme_light(base_size=15)+
  theme(
    plot.title=element_text(hjust=0.5),
    axis.title=element_text(face="bold")
  )

# 2.UScereal 

ggplot(data=UScereal,aes(x=vitamins,y=fat,fill=vitamins))+
  geom_violin()+
  geom_boxplot(width = 0.1)+
  labs(
    title="Grasas y vitaminas en cereales",
    x="Vitaminas",
    y="Grasas")+
  theme_minimal(base_size=15)+
  theme(
    plot.title=element_text(hjust=0.5),
    axis.title=element_text(face="bold")
  )

ggplot(data=UScereal,aes(x=shelf,y=fat,fill=shelf))+
  geom_point(alpha = 0.6)+
  geom_jitter(width = 0.2, height = 0.2)+
   geom_smooth(method = "lm")+
  labs(
    title="Cantidad de grasas en cereales",
    x="Cantidad en cereales",
    y="Grasa")+
  theme_minimal(base_size=15)+
  theme(
    plot.title=element_text(hjust=0.5),
    axis.title=element_text(face="bold")
  )
## `geom_smooth()` using formula = 'y ~ x'
## Warning: The following aesthetics were dropped during statistical transformation: fill.
## ℹ This can happen when ggplot fails to infer the correct grouping structure in
##   the data.
## ℹ Did you forget to specify a `group` aesthetic or to convert a numerical
##   variable into a factor?

ggplot(data=UScereal,aes(x=sugars,y=carbo))+
  geom_point(alpha = 0.7)+ #trasparencia 70%
    geom_smooth(method = "loess")+
  labs(
    title="Relacion entre azucares y carbohidratos en cereales",
    x="Azucar",
    y="Carbohidratos")+
  theme_minimal(base_size=15)+
  theme(
    legend.position = "bottom",
    plot.title=element_text(hjust=0.5),
    axis.title=element_text(face="bold")
  )
## `geom_smooth()` using formula = 'y ~ x'

#los cereales con mayor azucar también tienden a tener un mayor carbohidratos

#coeficiente de relacion 

correlacion <- cor(UScereal$sugars, UScereal$carbo)
print(correlacion)
## [1] -0.04082599
# el coeficiente de correlacion es negativa, lo que indica que hay una corrrelacion debil entre los azucares y carbohidratos puede ser a otros factores que no se estan teniendo en cuenta 
datos_agru<- UScereal%>%
  group_by(mfr) %>%
  summarise(almacenamiento_total= sum(fibre))%>%
  mutate(porcentaje = (almacenamiento_total/sum(almacenamiento_total))*100)


ggplot(data=datos_agru,aes(x=mfr,y=porcentaje,fill=mfr))+
  geom_col()+
   geom_text(aes(label=sprintf("%.1f%%", porcentaje)),vjust=1,colour="black")+
   labs(
    title="cantidad de fibra por fabricantes",
    x="Fabricantes",
    y="Fibra")+
  theme_minimal(base_size=15)+
  theme(
    plot.title=element_text(hjust=0.5),
    axis.title=element_text(face="bold")
  )

ggplot(data=UScereal,aes(x=sugars,y=sodium))+
  geom_point(alpha = 0.7)+ #trasparencia 70%
    geom_smooth(method = "loess")+
  labs(
    title="Relacion entre azucares y Sodio en cereales",
    x="Azucar",
    y="Sodio")+
  theme_minimal(base_size=15)+
  theme(
    legend.position = "bottom",
    plot.title=element_text(hjust=0.5),
    axis.title=element_text(face="bold")
  )
## `geom_smooth()` using formula = 'y ~ x'

#los cereales con mayor azucar también tienden a tener un mayor carbohidratos

#coeficiente de relacion 

correlacion <- cor(UScereal$sugars, UScereal$sodium)
print(correlacion)
## [1] 0.2112437
# 0.2112437  es una correlacion positiva lo cual indica que a medida que aumenta la cantida d de azuicar en un cereal tiende a aumentar el contenido de sodio, a apesar de ser positivo la relacion no es suficientemente fuerte  y pueden haber otros factores que influyan

# En general en promedio, los cereales con mayor contenido de azúcar tienden a tener un poco más de sodio
data("mammals")
str(mammals)
## 'data.frame':    62 obs. of  2 variables:
##  $ body : num  3.38 0.48 1.35 465 36.33 ...
##  $ brain: num  44.5 15.5 8.1 423 119.5 ...
ggplot(data=mammals,aes(x=brain,y=body))+
   geom_point(alpha = 0.7)+ #trasparencia 70%
    geom_smooth(method = "lm" )+
  labs(
    title="peso corporal y cerebral en mamiferos",
    x="Peso cerebral",
    y="Peso corporal")+
  theme_minimal(base_size=15)+
  theme(
    legend.position = "bottom",
    plot.title=element_text(hjust=0.5),
    axis.title=element_text(face="bold")
  )
## `geom_smooth()` using formula = 'y ~ x'

# La línea que se inclina hacia arriba,indica una correlacion positiva entre el peso cerebral y el peso corporal, es decir a medida que aumenta el peso corporal también tiende a aumentar el peso cerebral
# los puntos de dispersion estan cerca  de la linea y juntos lo que indica una relacion fuerte 

correlacion <- cor(mammals$brain, mammals$body)
print(correlacion)
## [1] 0.9341638
# 0.9341638 S e tiene una correlacion positova y muy alta 
# función logarítmica

mammals_log <- mammals %>%
  mutate(log_brain = log(brain),
         log_body = log(body))


ggplot(data = mammals_log, aes(x = log_brain, y = log_body)) +
  geom_point(alpha = 0.7) +
  geom_smooth(method = "lm") +
  labs(
    title = "peso corporal y cerebral en mamiferos(log)",
    x = "Log peso cerebral",
    y = "Log peso corporal"
  ) +
  theme_minimal(base_size = 15) +
  theme(
    legend.position = "bottom",
    plot.title = element_text(hjust = 0.5),
    axis.title = element_text(face = "bold")
  )
## `geom_smooth()` using formula = 'y ~ x'

# Gracias a la funcion logaritmica, la relacion de los datos se ven mejor no como en el enaterior que sabiamos que la relacion era grande pero visualmente no era tan claro
data("anorexia")
str(anorexia)
## 'data.frame':    72 obs. of  3 variables:
##  $ Treat : Factor w/ 3 levels "CBT","Cont","FT": 2 2 2 2 2 2 2 2 2 2 ...
##  $ Prewt : num  80.7 89.4 91.8 74 78.1 88.3 87.3 75.1 80.6 78.4 ...
##  $ Postwt: num  80.2 80.1 86.4 86.3 76.1 78.1 75.1 86.7 73.5 84.6 ...
# Calculo de la diferencia de peso y el promedio de esa diferencia por tratamiento usando aggregate
diferencia_peso <- aggregate(diff_peso ~ Treat, data = mutate(anorexia, diff_peso = Postwt - Prewt), FUN = mean)

print(diferencia_peso)
##   Treat diff_peso
## 1   CBT  3.006897
## 2  Cont -0.450000
## 3    FT  7.264706
ggplot(diferencia_peso, aes(x = Treat, y = diff_peso,fill=Treat)) +
  geom_col() +
   geom_text(aes(label=sprintf("%.1fkg", diff_peso)),vjuelst=-0.5,colour="black",position = position_dodge(width = 1))+
  scale_x_discrete(limits = c("FT","CBT","Cont"))+
  labs(
    x = "Tratamiento",
    y = "diff peso",
    title = "Eficacia de los tratamientos"
  )+
  theme_minimal(base_size=15)+
  theme(
    plot.title=element_text(hjust=0.5),
    axis.title=element_text(face="bold")
  )
## Warning in geom_text(aes(label = sprintf("%.1fkg", diff_peso)), vjuelst = -0.5,
## : Ignoring unknown parameters: `vjuelst`

# el tratamiento FT ha sido el más eficaz en terminos de ganancia de peso, seguido por CBT mientras que Cont muestra una perdida de peso promedio.
# Agregar una nueva variable para el cambio de peso
anorexia <- anorexia %>%
  mutate(weight_change = ifelse(Postwt - Prewt > 0, "Gano peso", "Perdio peso"))

# Contar el numero de pacientes que ganaron y perdieron peso
count_weight_change <- table(anorexia$weight_change)
#print(count_weight_change)

# Contar el numero de pacientes que ganaron y perdieron peso por tratamiento
count_weight_change_by_treatment <- table(anorexia$Treat, anorexia$weight_change)
#print(count_weight_change_by_treatment)


count_weight_change_by_treatment_df <- as.data.frame(count_weight_change_by_treatment)

# Verificar la estructura 
#str(count_weight_change_by_treatment_df)

ggplot(count_weight_change_by_treatment_df, aes(x = Var1, y = Freq,fill=Var2)) +
  geom_bar(stat = "identity", position = "dodge")+
  geom_text(aes(label = Freq), 
            vjust = -0.2,  
            colour = "black", 
            hjust = 0.5,  
            position = position_dodge(width = 0.9))+
  labs(
    title = "Pacientes que Ganaron y Perdieron Peso",
    x = "Tratamiento",
    y = "Numero de Pacientes",
    fill = "Cambio Peso"
  )

  theme_minimal(base_size = 10) +
  theme(
    plot.title = element_text(hjust = 0.5),
    axis.title = element_text(face = "bold"),
    legend.title = element_text(face = "bold")
  )
## List of 136
##  $ line                            :List of 6
##   ..$ colour       : chr "black"
##   ..$ linewidth    : num 0.455
##   ..$ 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.455
##   ..$ 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 10
##   ..$ 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                      :List of 11
##   ..$ family       : NULL
##   ..$ face         : chr "bold"
##   ..$ colour       : NULL
##   ..$ size         : NULL
##   ..$ hjust        : NULL
##   ..$ vjust        : NULL
##   ..$ angle        : NULL
##   ..$ lineheight   : NULL
##   ..$ margin       : NULL
##   ..$ debug        : NULL
##   ..$ inherit.blank: logi FALSE
##   ..- attr(*, "class")= chr [1:2] "element_text" "element"
##  $ 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.5points 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.5points 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.5points 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.5points
##   .. ..- 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        : NULL
##   ..$ vjust        : num 1
##   ..$ angle        : NULL
##   ..$ lineheight   : NULL
##   ..$ margin       : 'margin' num [1:4] 2points 0points 0points 0points
##   .. ..- attr(*, "unit")= int 8
##   ..$ debug        : NULL
##   ..$ inherit.blank: logi TRUE
##   ..- 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 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 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 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 2points 0points 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.5points
##   ..- 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] 5points 5points 5points 5points
##   ..- attr(*, "unit")= int 8
##  $ legend.spacing                  : 'simpleUnit' num 10points
##   ..- 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 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         : chr "bold"
##   ..$ colour       : NULL
##   ..$ size         : NULL
##   ..$ hjust        : num 0
##   ..$ vjust        : NULL
##   ..$ angle        : NULL
##   ..$ lineheight   : NULL
##   ..$ margin       : NULL
##   ..$ debug        : NULL
##   ..$ inherit.blank: logi FALSE
##   ..- 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 10points
##   ..- attr(*, "unit")= int 8
##   [list output truncated]
##  - attr(*, "class")= chr [1:2] "theme" "gg"
##  - attr(*, "complete")= logi TRUE
##  - attr(*, "validate")= logi TRUE