# Ejercicio 1
library()
# Cargo los paquetes instalados
library("MASS")
library("survival")

# Busco informaciĂłn sobre los paquetes
help(package="MASS")
help(package="survival")

# Busco informaciĂłn sobre el paquete Rcmdr
help(package="Rcmdr")
??Rcmdr
# Ejercicio 2
# apartado a)
# Importamos el archivo .txt indicando que tiene encabezados (header = TRUE) 
# y que las columnas estĂĄn separadas por espacios (sep = "")
mis_datos <- read.table("mis_ejercicios.txt", header = TRUE, sep = "")

# Confirmar la lectura visualizando las primeras filas
head(mis_datos)
##   paciente edad presion colesterol
## 1       P1   45     120        190
## 2       P2   52     135        210
## 3       P3   61     140        230
## 4       P4   38     115        175
## 5       P5   49     128        205
## 6       P6   65     150        245
# Calcular el summary() de las 3 variables cuantitativas
summary(mis_datos[, c("edad", "presion", "colesterol")])
##       edad          presion        colesterol   
##  Min.   :38.00   Min.   :115.0   Min.   :175.0  
##  1st Qu.:47.00   1st Qu.:124.0   1st Qu.:197.5  
##  Median :52.00   Median :130.0   Median :210.0  
##  Mean   :52.14   Mean   :131.1   Mean   :210.7  
##  3rd Qu.:58.00   3rd Qu.:137.5   3rd Qu.:225.0  
##  Max.   :65.00   Max.   :150.0   Max.   :245.0
# Ejercicio 2
# apartado b) Importar el archivo .csv
# Primero tengo que crear y guardar el archivo .csv directamente desde R
write.csv(mis_datos, "mis_pacientes.csv", row.names = FALSE)

# 2. Importar el archivo .csv (como pide el apartado b)
mis_datos_csv <- read.csv("mis_pacientes.csv")

# 3. Aplicar fivenum() sobre dos variables numéricas
fivenum(mis_datos_csv$edad)
## [1] 38 47 52 58 65
fivenum(mis_datos_csv$presion)
## [1] 115.0 124.0 130.0 137.5 150.0
# Ejercicio 3
library(MASS)
data("anorexia")
# Primero inspeccionamos la estructura y tipo de cada variable
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 ...
# Ver las primeras filas
head(anorexia)
##   Treat Prewt Postwt
## 1  Cont  80.7   80.2
## 2  Cont  89.4   80.1
## 3  Cont  91.8   86.4
## 4  Cont  74.0   86.3
## 5  Cont  78.1   76.1
## 6  Cont  88.3   78.1
# Compruebo el recuento de valores NA
table(is.na(anorexia))
## 
## FALSE 
##   216
# Comprobar si el objeto completo es NULL
table(is.null(anorexia))
## 
## FALSE 
##     1
# Reetiquetamos los niveles de la variable Treat
anorexia$Treat <- factor(anorexia$Treat,levels = c("CBT", "Cont", "FT"),labels = c("Cogn Beh Tr", "Contr", "Fam Tr"))

# Comprobar los nuevos niveles de la variable
levels(anorexia$Treat)
## [1] "Cogn Beh Tr" "Contr"       "Fam Tr"
head(anorexia)
##   Treat Prewt Postwt
## 1 Contr  80.7   80.2
## 2 Contr  89.4   80.1
## 3 Contr  91.8   86.4
## 4 Contr  74.0   86.3
## 5 Contr  78.1   76.1
## 6 Contr  88.3   78.1
# Ejercicio 4
# Apartado a)
library(MASS)
data("biopsy")

# Exportar a formato .csv en tu carpeta de trabajo
write.csv(biopsy, file = "biopsy.csv")

#Apartado b)
data("Melanoma")

# 1. Exportar a .csv
write.csv(Melanoma, file = "melanoma.csv")

# 2. Exportar a .txt
write.table(Melanoma, file = "melanoma.txt")

# 3. Exportar a .xlsx
# Se requiere cargar la librerĂ­a 'xlsx' u 'openxlsx'
library(openxlsx)
write.xlsx(Melanoma, file = "melanoma.xlsx")
# Apartado c)
# Obtener el resumen descriptivo de la variable 'age'
summary(Melanoma$age)
##    Min. 1st Qu.  Median    Mean 3rd Qu.    Max. 
##    4.00   42.00   54.00   52.46   65.00   95.00
# Apartado d)
# Importamos el dataset biomédico en .csv usando R Base (sin instalar paquetes)
datos_biomedicos <- read.csv("biopsy.csv")

# Visualizar los primeros registros para confirmar la lectura
head(datos_biomedicos)
##   X      ID V1 V2 V3 V4 V5 V6 V7 V8 V9     class
## 1 1 1000025  5  1  1  1  2  1  3  1  1    benign
## 2 2 1002945  5  4  4  5  7 10  3  2  1    benign
## 3 3 1015425  3  1  1  1  2  2  3  1  1    benign
## 4 4 1016277  6  8  8  1  3  4  3  7  1    benign
## 5 5 1017023  4  1  1  3  2  1  3  1  1    benign
## 6 6 1017122  8 10 10  8  7 10  9  7  1 malignant
# Ejercicio 5
library(MASS)
data("birthwt")

# Apartado a)
max(birthwt$age)
## [1] 45
# Apartado b)
min(birthwt$age)
## [1] 14
# Apartado c)
rango <- max(birthwt$age) - min(birthwt$age)
rango
## [1] 31
# Apartado d)
birthwt$smoke[birthwt$bwt == min(birthwt$bwt)]
## [1] 1
# Apartado e)
birthwt$bwt[birthwt$age == max(birthwt$age)]
## [1] 4990
# Apartado f)
birthwt$bwt[birthwt$ftv < 2]
##   [1] 2523 2557 2600 2622 2637 2637 2663 2665 2722 2733 2751 2769 2769 2778 2807
##  [16] 2821 2836 2863 2877 2906 2920 2920 2920 2948 2948 2977 2977 2922 3033 3062
##  [31] 3062 3062 3062 3090 3090 3100 3104 3132 3175 3175 3203 3203 3203 3225 3225
##  [46] 3232 3234 3260 3274 3317 3317 3331 3374 3374 3402 3416 3444 3459 3460 3473
##  [61] 3544 3487 3544 3572 3572 3586 3600 3614 3614 3629 3637 3643 3651 3651 3651
##  [76] 3651 3699 3728 3756 3770 3770 3770 3790 3799 3827 3884 3912 3940 3941 3941
##  [91] 3969 3997 3997 4054 4054 4111 4174 4238 4593 4990  709 1135 1330 1474 1588
## [106] 1588 1701 1729 1790 1818 1885 1893 1899 1928 1936 1970 2055 2055 2084 2084
## [121] 2100 2125 2187 2187 2211 2225 2240 2240 2282 2296 2296 2325 2353 2353 2367
## [136] 2381 2381 2381 2410 2410 2410 2424 2442 2466 2466 2495 2495
# Ejercicio 6
# Primero cargamos el paquete MASS y el dataset anorexia
library(MASS)
data(anorexia)

# Ahora creamos la matriz uniendo ambas columnas
matr_anorexia <- matrix(c(anorexia$Prewt, anorexia$Postwt), ncol = 2)

# 4. Mostrar las primeras filas de la matriz
head(matr_anorexia)
##      [,1] [,2]
## [1,] 80.7 80.2
## [2,] 89.4 80.1
## [3,] 91.8 86.4
## [4,] 74.0 86.3
## [5,] 78.1 76.1
## [6,] 88.3 78.1
# Ejercicio 7
# Primero preparamos los 6 vectores
Identificador <- c("I1","I2","I3","I4","I5","I6","I7","I8","I9","I10","I11","I12","I13","I14","I15","I16","I17","I18","I19","I20","I21","I22","I23","I24","I25")
Edad <- c(23,24,21,22,23,25,26,24,21,22,23,25,26,24,22,21,25,26,24,21,25,27,26,22,29)
Sexo <- c(1,2,1,1,1,2,2,2,1,2,1,2,2,2,1,1,1,2,2,2,1,2,1,1,2) # 1 para mujeres, 2 para hombres
Peso <- c(76.5,81.2,79.3,59.5,67.3,78.6,67.9,100.2,97.8,56.4,65.4,67.5,87.4,99.7,87.6,93.4,65.4,73.7,85.1,61.2,54.8,103.4,65.8,71.7,85.0)
Alt <- c(165,154,178,165,164,175,182,165,178,165,158,183,184,164,189,167,182,179,165,158,183,184,189,166,175)
Fuma <- c("SÍ","NO","SÍ","SÍ","NO","NO","NO","SÍ","SÍ","SÍ","NO","NO","SÍ","SÍ","SÍ","SÍ","NO","NO","SÍ","SÍ","SÍ","NO","SÍ","NO","SÍ")

Trat_Pulmon <- data.frame(Identificador, Edad, Sexo, Peso, Alt, Fuma)

# Apartado a) Registros con edad > 22
selec1 <- subset(Trat_Pulmon, Edad > 22)
selec1
##    Identificador Edad Sexo  Peso Alt Fuma
## 1             I1   23    1  76.5 165   SÍ
## 2             I2   24    2  81.2 154   NO
## 5             I5   23    1  67.3 164   NO
## 6             I6   25    2  78.6 175   NO
## 7             I7   26    2  67.9 182   NO
## 8             I8   24    2 100.2 165   SÍ
## 11           I11   23    1  65.4 158   NO
## 12           I12   25    2  67.5 183   NO
## 13           I13   26    2  87.4 184   SÍ
## 14           I14   24    2  99.7 164   SÍ
## 17           I17   25    1  65.4 182   NO
## 18           I18   26    2  73.7 179   NO
## 19           I19   24    2  85.1 165   SÍ
## 21           I21   25    1  54.8 183   SÍ
## 22           I22   27    2 103.4 184   NO
## 23           I23   26    1  65.8 189   SÍ
## 25           I25   29    2  85.0 175   SÍ
# Apartado b) Elemento en la fila 3, columna 4
selec2 <- Trat_Pulmon[5, 6]
selec2
## [1] "NO"
# Apartado c) Filas con edad < 27 excluyendo la columna Alt
selec3 <- subset(Trat_Pulmon, Edad < 27, select = -c(Alt))
selec3
##    Identificador Edad Sexo  Peso Fuma
## 1             I1   23    1  76.5   SÍ
## 2             I2   24    2  81.2   NO
## 3             I3   21    1  79.3   SÍ
## 4             I4   22    1  59.5   SÍ
## 5             I5   23    1  67.3   NO
## 6             I6   25    2  78.6   NO
## 7             I7   26    2  67.9   NO
## 8             I8   24    2 100.2   SÍ
## 9             I9   21    1  97.8   SÍ
## 10           I10   22    2  56.4   SÍ
## 11           I11   23    1  65.4   NO
## 12           I12   25    2  67.5   NO
## 13           I13   26    2  87.4   SÍ
## 14           I14   24    2  99.7   SÍ
## 15           I15   22    1  87.6   SÍ
## 16           I16   21    1  93.4   SÍ
## 17           I17   25    1  65.4   NO
## 18           I18   26    2  73.7   NO
## 19           I19   24    2  85.1   SÍ
## 20           I20   21    2  61.2   SÍ
## 21           I21   25    1  54.8   SÍ
## 23           I23   26    1  65.8   SÍ
## 24           I24   22    1  71.7   NO
# Ejercicio 8 
# Apartado a) Cargar el dataset ChickWeight del paquete datasets
library(datasets)
data("ChickWeight")
head(ChickWeight)
##   weight Time Chick Diet
## 1     42    0     1    1
## 2     51    2     1    1
## 3     59    4     1    1
## 4     64    6     1    1
## 5     76    8     1    1
## 6     93   10     1    1
# Apartado b) 
plot(ChickWeight$weight, col = "red", main = "GrĂĄfico de DispersiĂłn - Peso")

# Apartado c)
boxplot(ChickWeight$Time, col = "pink", main = "Diagrama de Caja - Tiempo")

# Ejercicio 9
# Primero cargamos el paquete MASS y los datos
library(MASS)
data("anorexia")

# Calculamos la diferencia de peso final menos inicial (Postwt - Prewt)
post_pre_v <- anorexia$Postwt - anorexia$Prewt

# Creamos el data frame combinado anorexia_treat_df
anorexia_treat_df <- data.frame(anorexia, post_pre_v)
head(anorexia_treat_df)
##   Treat Prewt Postwt post_pre_v
## 1  Cont  80.7   80.2       -0.5
## 2  Cont  89.4   80.1       -9.3
## 3  Cont  91.8   86.4       -5.4
## 4  Cont  74.0   86.3       12.3
## 5  Cont  78.1   76.1       -2.0
## 6  Cont  88.3   78.1      -10.2
# Por Ășltimo filtramos pacientes del grupo "Cont" que han ganado peso (post_pre_v > 0)
anorexia_treat_C_df <- subset(anorexia_treat_df, Treat == "Cont" & post_pre_v > 0)

# Visualizamos el resultado filtrado
head(anorexia_treat_C_df)
##    Treat Prewt Postwt post_pre_v
## 4   Cont  74.0   86.3       12.3
## 8   Cont  75.1   86.7       11.6
## 10  Cont  78.4   84.6        6.2
## 13  Cont  81.3   89.6        8.3
## 14  Cont  78.1   81.4        3.3
## 15  Cont  70.5   81.8       11.3