Ejercicio 1:

Para comprobar los paquetes instalados:

sessionInfo()
## R version 4.6.1 (2026-06-24 ucrt)
## Platform: x86_64-w64-mingw32/x64
## Running under: Windows 11 x64 (build 26200)
## 
## Matrix products: default
##   LAPACK version 3.12.1
## 
## locale:
## [1] LC_COLLATE=English_United Kingdom.utf8 
## [2] LC_CTYPE=English_United Kingdom.utf8   
## [3] LC_MONETARY=English_United Kingdom.utf8
## [4] LC_NUMERIC=C                           
## [5] LC_TIME=English_United Kingdom.utf8    
## 
## time zone: Europe/Tallinn
## tzcode source: internal
## 
## attached base packages:
## [1] stats     graphics  grDevices utils     datasets  methods   base     
## 
## loaded via a namespace (and not attached):
##  [1] digest_0.6.39     R6_2.6.1          fastmap_1.2.0     xfun_0.61        
##  [5] cachem_1.1.0      knitr_1.52        htmltools_0.5.9   rmarkdown_2.32   
##  [9] lifecycle_1.0.5   cli_3.6.6         sass_0.4.10       jquerylib_0.1.4  
## [13] compiler_4.6.1    rstudioapi_0.19.0 tools_4.6.1       evaluate_1.0.5   
## [17] bslib_0.12.0      yaml_2.3.12       rlang_1.3.0       jsonlite_2.0.0
library()

Para instalar los paquetes MASS y survival:

install.packages(c("MASS","Survival"))

Para comprobrar la información de los paquetes instalados:

packageDescription("MASS")
packageDescription("survival")

Para obtener información sobre un paquete específico:

??Rcmdr
## starting httpd help server ... done

Ejercicio 2:

Para cargar un archivo de texto y buscar un summary() de tres variables:

hg38_RefSeq <- read.csv("~/UOC/Semestre 2/Software para el Análisis de datos/Reto1_InstalacionEstadisticaDescriptiva/LAB1/hg38_RefSeq.txt", sep="")
summary(hg38_RefSeq[, c("name","strand","cdsStart")])
##         name              strand          cdsStart        
##  Length   :172766   Length   :172766   Min.   :        0  
##  N.unique :163988   N.unique :     2   1st Qu.: 25925963  
##  N.blank  :     0   N.blank  :     0   Median : 56468697  
##  Min.nchar:    11   Min.nchar:     1   Mean   : 70879841  
##  Max.nchar:    14   Max.nchar:     1   3rd Qu.:108149909  
##                                        Max.   :248917337

Para importar un archivo .csv y buscar un fivenum() de dos variables:

pinguinos <- read.csv("~/UOC/Semestre 2/Software para el Análisis de datos/Reto1_InstalacionEstadisticaDescriptiva/LAB1/penguins.csv")
fivenum(pinguinos$body_mass_g)
## [1] 2700 3550 4050 4750 6300
fivenum(pinguinos$flipper_length_mm)
## [1] 172 190 197 213 231

Ejercicio 3:

Para cargar el conjunto de datos anorexia del paquete MASS y mostrar los tipos de datos que contiene:

library(MASS)
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 ...
summary(anorexia)
##   Treat        Prewt           Postwt      
##  CBT :29   Min.   :70.00   Min.   : 71.30  
##  Cont:26   1st Qu.:79.60   1st Qu.: 79.33  
##  FT  :17   Median :82.30   Median : 84.05  
##            Mean   :82.41   Mean   : 85.17  
##            3rd Qu.:86.00   3rd Qu.: 91.55  
##            Max.   :94.90   Max.   :103.60

Para comprobar si en el conjunto de datos existen los valores NA y NULL:

sum(is.na(anorexia))
## [1] 0
is.null(anorexia)
## [1] FALSE

Para transformar los nombres de los valores CBT, Cont y FT en la variable Treat:

levels(anorexia$Treat) <- c("Cogn Beh Tr","Contr","Fam Tr")
str(anorexia)
## 'data.frame':    72 obs. of  3 variables:
##  $ Treat : Factor w/ 3 levels "Cogn Beh Tr",..: 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 ...
summary(anorexia$Treat)
## Cogn Beh Tr       Contr      Fam Tr 
##          29          26          17

Ejercicio 4:

Para exportar los datos biopsy del paquete MASS a un archivo .csv:

library(MASS)
data("biopsy")
head(biopsy)
##        ID V1 V2 V3 V4 V5 V6 V7 V8 V9     class
## 1 1000025  5  1  1  1  2  1  3  1  1    benign
## 2 1002945  5  4  4  5  7 10  3  2  1    benign
## 3 1015425  3  1  1  1  2  2  3  1  1    benign
## 4 1016277  6  8  8  1  3  4  3  7  1    benign
## 5 1017023  4  1  1  3  2  1  3  1  1    benign
## 6 1017122  8 10 10  8  7 10  9  7  1 malignant
write.csv(biopsy,file="~/UOC/Semestre 2/Software para el Análisis de datos/Reto1_InstalacionEstadisticaDescriptiva/LAB1/biopsy.csv")

Para generar tres archivos con diferentes formatos de los datos Melanoma del paquete MASS:

library(MASS)
data("Melanoma")
head(Melanoma)
##   time status sex age year thickness ulcer
## 1   10      3   1  76 1972      6.76     1
## 2   30      3   1  56 1968      0.65     0
## 3   35      2   1  41 1977      1.34     0
## 4   99      3   0  71 1968      2.90     0
## 5  185      1   1  52 1965     12.08     1
## 6  204      1   1  28 1971      4.84     1
write.table(Melanoma,file="~/UOC/Semestre 2/Software para el Análisis de datos/Reto1_InstalacionEstadisticaDescriptiva/LAB1/Melanoma1.txt")
write.csv(Melanoma,file="~/UOC/Semestre 2/Software para el Análisis de datos/Reto1_InstalacionEstadisticaDescriptiva/LAB1/Melanoma2.csv")
library(foreign)
write.foreign(Melanoma,"~/UOC/Semestre 2/Software para el Análisis de datos/Reto1_InstalacionEstadisticaDescriptiva/LAB1/Melanoma1.txt","~/UOC/Semestre 2/Software para el Análisis de datos/Reto1_InstalacionEstadisticaDescriptiva/LAB1/Melanoma3", package="SAS")
Imagen 1. Comprobación de la creación de los archivos con diferentes formatos
Imagen 1. Comprobación de la creación de los archivos con diferentes formatos

Para generar un archivo .doc luego de generar un resumen de la variable Age:

Age = summary(Melanoma$age)
capture.output(Age,file="Age_Melanoma.doc")

Para importar el conjunto de datos .csv obtenido a partir del repositorio https://ouhsc.edu/bserdac/dthompso/web/statres.htm sobre el consumo de alcohol en el estado de Alabama en el año 1999:

datos <- read.csv("~/UOC/Semestre 2/Software para el Análisis de datos/Reto1_InstalacionEstadisticaDescriptiva/LAB1/NCCD_COVE_API.csv")
head(datos)
##     X95..CI BreakOutCategoryId BreakOutId Category Category_DisplayOrder
## 1   2.1-3.9               CAT1        BO1  Overall                     1
## 2   1.8-3.4               CAT1        BO1  Overall                     1
## 3   2.2-4.0               CAT1        BO1  Overall                     1
## 4 96.1-97.9               CAT1        BO1  Overall                     1
## 5 96.6-98.2               CAT1        BO1  Overall                     1
## 6 96.0-97.8               CAT1        BO1  Overall                     1
##                 Class ClassId Class_DisplayOrder                     Createdon
## 1 Alcohol Consumption CLASS01                  1 Tue, 15 Sep 2026 13:58:03 GMT
## 2 Alcohol Consumption CLASS01                  1 Tue, 15 Sep 2026 13:58:03 GMT
## 3 Alcohol Consumption CLASS01                  1 Tue, 15 Sep 2026 13:58:03 GMT
## 4 Alcohol Consumption CLASS01                  1 Tue, 15 Sep 2026 13:58:03 GMT
## 5 Alcohol Consumption CLASS01                  1 Tue, 15 Sep 2026 13:58:03 GMT
## 6 Alcohol Consumption CLASS01                  1 Tue, 15 Sep 2026 13:58:03 GMT
##   DataSource        Data_Type Data_Value_Format    Dataset Footnotes
## 1      BRFSS Crude Prevalence               3.0 Nationwide        NA
## 2      BRFSS Crude Prevalence               2.6 Nationwide        NA
## 3      BRFSS Crude Prevalence               3.1 Nationwide        NA
## 4      BRFSS Crude Prevalence              97.0 Nationwide        NA
## 5      BRFSS Crude Prevalence              97.4 Nationwide        NA
## 6      BRFSS Crude Prevalence              96.9 Nationwide        NA
##   Footnotes_Symbol GeoLocation_Lat GeoLocation_Long High_CI LocationCategory
## 1               NA        32.84057        -86.63186     3.9           States
## 2               NA        32.84057        -86.63186     3.4           States
## 3               NA        32.84057        -86.63186     4.0           States
## 4               NA        32.84057        -86.63186    97.9           States
## 5               NA        32.84057        -86.63186    98.2           States
## 6               NA        32.84057        -86.63186    97.8           States
##   LocationId Location_DisplayOrder Low_CI Percentage Percentage_Format
## 1          1                     3    2.1        3.0               3.0
## 2          1                     3    1.8        2.6               2.6
## 3          1                     3    2.2        3.1               3.1
## 4          1                     3   96.1       97.0              97.0
## 5          1                     3   96.6       97.4              97.4
## 6          1                     3   96.0       96.9              96.9
##                                                                                                                                                Question
## 1 Chronic drinkers (adult respondents having more than 60 alcoholic beverages in the past month) (variable calculated from one or more BRFSS questions)
## 2 Chronic drinkers (adult respondents having more than 60 alcoholic beverages in the past month) (variable calculated from one or more BRFSS questions)
## 3 Chronic drinkers (adult respondents having more than 60 alcoholic beverages in the past month) (variable calculated from one or more BRFSS questions)
## 4 Chronic drinkers (adult respondents having more than 60 alcoholic beverages in the past month) (variable calculated from one or more BRFSS questions)
## 5 Chronic drinkers (adult respondents having more than 60 alcoholic beverages in the past month) (variable calculated from one or more BRFSS questions)
## 6 Chronic drinkers (adult respondents having more than 60 alcoholic beverages in the past month) (variable calculated from one or more BRFSS questions)
##   QuestionId
## 1   _RFDRCHR
## 2   _RFDRCHR
## 3   _RFDRCHR
## 4   _RFDRCHR
## 5   _RFDRCHR
## 6   _RFDRCHR
##                                                                                                                                           Question_Code
## 1 Chronic drinkers (adult respondents having more than 60 alcoholic beverages in the past month) (variable calculated from one or more BRFSS questions)
## 2 Chronic drinkers (adult respondents having more than 60 alcoholic beverages in the past month) (variable calculated from one or more BRFSS questions)
## 3 Chronic drinkers (adult respondents having more than 60 alcoholic beverages in the past month) (variable calculated from one or more BRFSS questions)
## 4 Chronic drinkers (adult respondents having more than 60 alcoholic beverages in the past month) (variable calculated from one or more BRFSS questions)
## 5 Chronic drinkers (adult respondents having more than 60 alcoholic beverages in the past month) (variable calculated from one or more BRFSS questions)
## 6 Chronic drinkers (adult respondents having more than 60 alcoholic beverages in the past month) (variable calculated from one or more BRFSS questions)
##   Question_DisplayOrder Question_Year Response ResponseId Response_DisplayOrder
## 1                     1          1999      Yes    RESP046                     1
## 2                     1          1999      Yes    RESP046                     1
## 3                     1          1999      Yes    RESP046                     1
## 4                     1          1999       No    RESP054                     9
## 5                     1          1999       No    RESP054                     9
## 6                     1          1999       No    RESP054                     9
##   Response_Filter Series Series_DisplayOrder   State State_Abbr State_Code
## 1   All Responses    Yes                   1 Alabama         AL    Alabama
## 2   All Responses    Yes                   1 Alabama         AL    Alabama
## 3   All Responses    Yes                   1 Alabama         AL    Alabama
## 4   All Responses     No                   9 Alabama         AL    Alabama
## 5   All Responses     No                   9 Alabama         AL    Alabama
## 6   All Responses     No                   9 Alabama         AL    Alabama
##   Subcategory Subcategory_DisplayOrder            Topic TopicId
## 1     Overall                        1 Chronic Drinking TOPIC13
## 2     Overall                        1 Chronic Drinking TOPIC13
## 3     Overall                        1 Chronic Drinking TOPIC13
## 4     Overall                        1 Chronic Drinking TOPIC13
## 5     Overall                        1 Chronic Drinking TOPIC13
## 6     Overall                        1 Chronic Drinking TOPIC13
##   Topic_DisplayOrder Year Year_Pivot_Display    n
## 1                  3 1997               Year   55
## 2                  3 1995               Year   45
## 3                  3 1999               Year   64
## 4                  3 1997               Year 2059
## 5                  3 1995               Year 1705
## 6                  3 1999               Year 1994
str(datos)
## 'data.frame':    6 obs. of  46 variables:
##  $ X95..CI                 : chr  "2.1-3.9" "1.8-3.4" "2.2-4.0" "96.1-97.9" ...
##  $ BreakOutCategoryId      : chr  "CAT1" "CAT1" "CAT1" "CAT1" ...
##  $ BreakOutId              : chr  "BO1" "BO1" "BO1" "BO1" ...
##  $ Category                : chr  "Overall" "Overall" "Overall" "Overall" ...
##  $ Category_DisplayOrder   : int  1 1 1 1 1 1
##  $ Class                   : chr  "Alcohol Consumption" "Alcohol Consumption" "Alcohol Consumption" "Alcohol Consumption" ...
##  $ ClassId                 : chr  "CLASS01" "CLASS01" "CLASS01" "CLASS01" ...
##  $ Class_DisplayOrder      : int  1 1 1 1 1 1
##  $ Createdon               : chr  "Tue, 15 Sep 2026 13:58:03 GMT" "Tue, 15 Sep 2026 13:58:03 GMT" "Tue, 15 Sep 2026 13:58:03 GMT" "Tue, 15 Sep 2026 13:58:03 GMT" ...
##  $ DataSource              : chr  "BRFSS" "BRFSS" "BRFSS" "BRFSS" ...
##  $ Data_Type               : chr  "Crude Prevalence" "Crude Prevalence" "Crude Prevalence" "Crude Prevalence" ...
##  $ Data_Value_Format       : num  3 2.6 3.1 97 97.4 96.9
##  $ Dataset                 : chr  "Nationwide" "Nationwide" "Nationwide" "Nationwide" ...
##  $ Footnotes               : logi  NA NA NA NA NA NA
##  $ Footnotes_Symbol        : logi  NA NA NA NA NA NA
##  $ GeoLocation_Lat         : num  32.8 32.8 32.8 32.8 32.8 ...
##  $ GeoLocation_Long        : num  -86.6 -86.6 -86.6 -86.6 -86.6 ...
##  $ High_CI                 : num  3.9 3.4 4 97.9 98.2 97.8
##  $ LocationCategory        : chr  "States" "States" "States" "States" ...
##  $ LocationId              : int  1 1 1 1 1 1
##  $ Location_DisplayOrder   : int  3 3 3 3 3 3
##  $ Low_CI                  : num  2.1 1.8 2.2 96.1 96.6 96
##  $ Percentage              : num  3 2.6 3.1 97 97.4 96.9
##  $ Percentage_Format       : num  3 2.6 3.1 97 97.4 96.9
##  $ Question                : chr  "Chronic drinkers (adult respondents having more than 60 alcoholic beverages in the past month) (variable calcul"| __truncated__ "Chronic drinkers (adult respondents having more than 60 alcoholic beverages in the past month) (variable calcul"| __truncated__ "Chronic drinkers (adult respondents having more than 60 alcoholic beverages in the past month) (variable calcul"| __truncated__ "Chronic drinkers (adult respondents having more than 60 alcoholic beverages in the past month) (variable calcul"| __truncated__ ...
##  $ QuestionId              : chr  "_RFDRCHR" "_RFDRCHR" "_RFDRCHR" "_RFDRCHR" ...
##  $ Question_Code           : chr  "Chronic drinkers (adult respondents having more than 60 alcoholic beverages in the past month) (variable calcul"| __truncated__ "Chronic drinkers (adult respondents having more than 60 alcoholic beverages in the past month) (variable calcul"| __truncated__ "Chronic drinkers (adult respondents having more than 60 alcoholic beverages in the past month) (variable calcul"| __truncated__ "Chronic drinkers (adult respondents having more than 60 alcoholic beverages in the past month) (variable calcul"| __truncated__ ...
##  $ Question_DisplayOrder   : int  1 1 1 1 1 1
##  $ Question_Year           : int  1999 1999 1999 1999 1999 1999
##  $ Response                : chr  "Yes" "Yes" "Yes" "No" ...
##  $ ResponseId              : chr  "RESP046" "RESP046" "RESP046" "RESP054" ...
##  $ Response_DisplayOrder   : int  1 1 1 9 9 9
##  $ Response_Filter         : chr  "All Responses" "All Responses" "All Responses" "All Responses" ...
##  $ Series                  : chr  "Yes" "Yes" "Yes" "No" ...
##  $ Series_DisplayOrder     : int  1 1 1 9 9 9
##  $ State                   : chr  "Alabama" "Alabama" "Alabama" "Alabama" ...
##  $ State_Abbr              : chr  "AL" "AL" "AL" "AL" ...
##  $ State_Code              : chr  "Alabama" "Alabama" "Alabama" "Alabama" ...
##  $ Subcategory             : chr  "Overall" "Overall" "Overall" "Overall" ...
##  $ Subcategory_DisplayOrder: int  1 1 1 1 1 1
##  $ Topic                   : chr  "Chronic Drinking" "Chronic Drinking" "Chronic Drinking" "Chronic Drinking" ...
##  $ TopicId                 : chr  "TOPIC13" "TOPIC13" "TOPIC13" "TOPIC13" ...
##  $ Topic_DisplayOrder      : int  3 3 3 3 3 3
##  $ Year                    : int  1997 1995 1999 1997 1995 1999
##  $ Year_Pivot_Display      : chr  "Year" "Year" "Year" "Year" ...
##  $ n                       : int  55 45 64 2059 1705 1994

Ejercicio 5:

Para cargar el conjunto de datos birthwt:

data("birthwt")
head(birthwt)
##    low age lwt race smoke ptl ht ui ftv  bwt
## 85   0  19 182    2     0   0  0  1   0 2523
## 86   0  33 155    3     0   0  0  0   3 2551
## 87   0  20 105    1     1   0  0  0   1 2557
## 88   0  21 108    1     1   0  0  1   2 2594
## 89   0  18 107    1     1   0  0  1   0 2600
## 91   0  21 124    3     0   0  0  0   0 2622

Para saber la edad máxima de las madres en el conjunto de datos:

max(birthwt$age)
## [1] 45

Para saber la edad mínima de las madres en el conjunto de datos:

min(birthwt$age)
## [1] 14

Para saber el rango de edad de las madres en el conjunto de datos:

range(birthwt$age)
## [1] 14 45

Para saber si la madre, cuyo recién nacido fue el de menor peso, fumaba:

birthwt$smoke[birthwt$bwt==min(birthwt$bwt)]
## [1] 1

Para saber cuánto pesó el recién nacido cuya madre tenía la edad máxima:

birthwt$bwt[birthwt$age==max(birthwt$age)]
## [1] 4990

Para saber los pesos de los recién nacidos cuyas madres visitarán menos de dos veces al médico durante el primer trimestre:

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:

Para crear una matriz de dos columnas con los valores de Prewt y Postwt del conjunto de datos anorexia, en donde cada fila sean los valores correspondientes para cada posición:

library("MASS")
data("anorexia")
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
matriz_pesos <- cbind(Prewt=anorexia$Prewt, Postwt=anorexia$Postwt)
head(matriz_pesos)
##      Prewt Postwt
## [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
class(matriz_pesos)
## [1] "matrix" "array"

Ejercicio 7:

Para generar un data frame con 25 registros y 6 variables:

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 y 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) #altura en cm
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)
Trat_Pulmon
##    Identificador Edad Sexo  Peso Alt Fuma
## 1             I1   23    1  76.5 165   SÍ
## 2             I2   24    2  81.2 154   NO
## 3             I3   21    1  79.3 178   SÍ
## 4             I4   22    1  59.5 165   SÍ
## 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Í
## 9             I9   21    1  97.8 178   SÍ
## 10           I10   22    2  56.4 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Í
## 15           I15   22    1  87.6 189   SÍ
## 16           I16   21    1  93.4 167   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Í
## 20           I20   21    2  61.2 158   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Í
## 24           I24   22    1  71.7 166   NO
## 25           I25   29    2  85.0 175   SÍ

Para seleccionar los resgistros con edad > 22:

Trat_Pulmon[Trat_Pulmon$Edad > 22,]
##    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Í

Para seleccionar el elemento 3 de la columna 4 del conjunto de datos:

Trat_Pulmon[3,4]
## [1] 79.3

Para seleccionar todas las filas que tienen una edad < 27 y sin incluir la columna Alt:

Trat_Pulmon2 <- subset(Trat_Pulmon, Edad<27, select=-c(Alt))
Trat_Pulmon2
##    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:

Para incorporar el conjunto de datos 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

Para generar un gráfico de dispersión con la variable weight:

plot(ChickWeight$weight, main="Diagrama de dispersión de la variable Weight", ylab="Weight (g)")

Para generar un diagrama de caja con la variable Time:

boxplot(ChickWeight$Time, main="Diagrama de caja de la variable Time", ylab="Time (days)", col="orange")

Ejercicio 9:

Para cargar los datos del conjunto de datos anorexia:

library(MASS)
data("anorexia")
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

Para crear un data frame en el que se incorpore la variable Treat y una nueva variable correspondiente a la diferencia Prewt-Postwt:

diferencia_peso <- anorexia$Prewt-anorexia$Postwt
anorexia_treat_df <- data.frame(Treat=anorexia$Treat, Df=diferencia_peso)
anorexia_treat_df
##    Treat    Df
## 1   Cont   0.5
## 2   Cont   9.3
## 3   Cont   5.4
## 4   Cont -12.3
## 5   Cont   2.0
## 6   Cont  10.2
## 7   Cont  12.2
## 8   Cont -11.6
## 9   Cont   7.1
## 10  Cont  -6.2
## 11  Cont   0.2
## 12  Cont   9.2
## 13  Cont  -8.3
## 14  Cont  -3.3
## 15  Cont -11.3
## 16  Cont   0.0
## 17  Cont   1.0
## 18  Cont  10.6
## 19  Cont   4.6
## 20  Cont   6.7
## 21  Cont  -2.8
## 22  Cont  -0.3
## 23  Cont  -1.8
## 24  Cont  -3.7
## 25  Cont -15.9
## 26  Cont  10.2
## 27   CBT  -1.7
## 28   CBT  -0.7
## 29   CBT   0.1
## 30   CBT   0.7
## 31   CBT   3.5
## 32   CBT -14.9
## 33   CBT  -3.5
## 34   CBT -17.1
## 35   CBT   7.6
## 36   CBT  -1.6
## 37   CBT -11.7
## 38   CBT  -6.1
## 39   CBT  -1.1
## 40   CBT   4.0
## 41   CBT -20.9
## 42   CBT   9.1
## 43   CBT  -2.1
## 44   CBT   1.4
## 45   CBT  -1.4
## 46   CBT   0.3
## 47   CBT   3.7
## 48   CBT   0.8
## 49   CBT  -2.4
## 50   CBT -12.6
## 51   CBT  -1.9
## 52   CBT  -3.9
## 53   CBT  -0.1
## 54   CBT -15.4
## 55   CBT   0.7
## 56    FT -11.4
## 57    FT -11.0
## 58    FT  -5.5
## 59    FT  -9.4
## 60    FT -13.6
## 61    FT   2.9
## 62    FT   0.1
## 63    FT  -7.4
## 64    FT -21.5
## 65    FT   5.3
## 66    FT   3.8
## 67    FT -13.4
## 68    FT -13.1
## 69    FT  -9.0
## 70    FT  -3.9
## 71    FT  -5.7
## 72    FT -10.7

Para seleccionar los individuos que han ganado peso después del tratamiento:

anorexia_treat_df[anorexia_treat_df$Df>0,]
##    Treat   Df
## 1   Cont  0.5
## 2   Cont  9.3
## 3   Cont  5.4
## 5   Cont  2.0
## 6   Cont 10.2
## 7   Cont 12.2
## 9   Cont  7.1
## 11  Cont  0.2
## 12  Cont  9.2
## 17  Cont  1.0
## 18  Cont 10.6
## 19  Cont  4.6
## 20  Cont  6.7
## 26  Cont 10.2
## 29   CBT  0.1
## 30   CBT  0.7
## 31   CBT  3.5
## 35   CBT  7.6
## 40   CBT  4.0
## 42   CBT  9.1
## 44   CBT  1.4
## 46   CBT  0.3
## 47   CBT  3.7
## 48   CBT  0.8
## 55   CBT  0.7
## 61    FT  2.9
## 62    FT  0.1
## 65    FT  5.3
## 66    FT  3.8

Para crear un nuevo conjunto que contenga solo los datos de los individuos que han ganado peso y los que han seguido el tratamiento Cont:

library(dplyr)
## 
## Attaching package: 'dplyr'
## The following object is masked from 'package:MASS':
## 
##     select
## The following objects are masked from 'package:stats':
## 
##     filter, lag
## The following objects are masked from 'package:base':
## 
##     intersect, setdiff, setequal, union
anorexia_treat_C_df <- filter(anorexia_treat_df, Df >0 & Treat=="Cont")
anorexia_treat_C_df
##    Treat   Df
## 1   Cont  0.5
## 2   Cont  9.3
## 3   Cont  5.4
## 4   Cont  2.0
## 5   Cont 10.2
## 6   Cont 12.2
## 7   Cont  7.1
## 8   Cont  0.2
## 9   Cont  9.2
## 10  Cont  1.0
## 11  Cont 10.6
## 12  Cont  4.6
## 13  Cont  6.7
## 14  Cont 10.2

Ejercicio 10:

library(knitr)

El enlace para visualizar la resolución del LAB1 publicado en RPubs

Caso práctico:

Para crear un conjunto de datos inventado con 30 observaciones (15 para hombres y 15 para mujeres) y 6 variables.

set.seed(123)
Id <- 1:30
Edad <- round(rnorm(30, mean=35, sd=5))
Gene <- sample(rep(c(1,2),each=15))
Trat <- sample(c("A", "B", "C"), size=30, replace=TRUE)
Peso <- round(rnorm(30, mean=70, sd=10))
Alt <- round(rnorm(30, mean=170, sd=8))
Midataf <- data.frame(Id, Edad, Gene, Trat, Peso, Alt)
Midataf
##    Id Edad Gene Trat Peso Alt
## 1   1   32    1    B   65 164
## 2   2   34    1    A   47 172
## 3   3   43    1    B   80 168
## 4   4   35    1    A   63 167
## 5   5   36    2    C   63 162
## 6   6   44    1    C   80 170
## 7   7   37    1    B   67 164
## 8   8   29    2    C   58 157
## 9   9   32    1    A   72 167
## 10 10   33    1    B   69 177
## 11 11   41    2    B   70 165
## 12 12   37    2    C   74 175
## 13 13   37    2    B   66 157
## 14 14   36    1    A   76 170
## 15 15   32    2    C   68 174
## 16 16   44    2    C   73 172
## 17 17   37    2    C   81 171
## 18 18   25    1    B   74 165
## 19 19   39    2    B   67 163
## 20 20   33    1    C   81 162
## 21 21   30    1    A   80 171
## 22 22   34    2    A   75 162
## 23 23   30    1    C   72 166
## 24 24   31    1    B   64 168
## 25 25   32    2    B   84 185
## 26 26   27    2    B   64 165
## 27 27   39    2    B   92 172
## 28 28   36    1    B   85 171
## 29 29   29    2    B   68 162
## 30 30   41    2    C   60 169

Para visualizar la información del conjunto de datos:

dim(Midataf)
## [1] 30  6
length(Midataf)
## [1] 6
head(Midataf)
##   Id Edad Gene Trat Peso Alt
## 1  1   32    1    B   65 164
## 2  2   34    1    A   47 172
## 3  3   43    1    B   80 168
## 4  4   35    1    A   63 167
## 5  5   36    2    C   63 162
## 6  6   44    1    C   80 170
names(Midataf)
## [1] "Id"   "Edad" "Gene" "Trat" "Peso" "Alt"
str(Midataf)
## 'data.frame':    30 obs. of  6 variables:
##  $ Id  : int  1 2 3 4 5 6 7 8 9 10 ...
##  $ Edad: num  32 34 43 35 36 44 37 29 32 33 ...
##  $ Gene: num  1 1 1 1 2 1 1 2 1 1 ...
##  $ Trat: chr  "B" "A" "B" "A" ...
##  $ Peso: num  65 47 80 63 63 80 67 58 72 69 ...
##  $ Alt : num  164 172 168 167 162 170 164 157 167 177 ...
summary(Midataf)
##        Id             Edad            Gene            Trat         Peso      
##  Min.   : 1.00   Min.   :25.00   Min.   :1.0   Length   :30   Min.   :47.00  
##  1st Qu.: 8.25   1st Qu.:32.00   1st Qu.:1.0   N.unique : 3   1st Qu.:65.25  
##  Median :15.50   Median :34.50   Median :1.5   N.blank  : 0   Median :71.00  
##  Mean   :15.50   Mean   :34.83   Mean   :1.5   Min.nchar: 1   Mean   :71.27  
##  3rd Qu.:22.75   3rd Qu.:37.00   3rd Qu.:2.0   Max.nchar: 1   3rd Qu.:79.00  
##  Max.   :30.00   Max.   :44.00   Max.   :2.0                  Max.   :92.00  
##       Alt       
##  Min.   :157.0  
##  1st Qu.:164.0  
##  Median :167.5  
##  Mean   :167.8  
##  3rd Qu.:171.0  
##  Max.   :185.0

Para crear una nueva variable llamada IMC, usando variables existentes, e incorporarla en el conjunto de datos original:

Midataf$IMC <- Midataf$Peso/((Midataf$Alt/100)^2)
Midataf
##    Id Edad Gene Trat Peso Alt      IMC
## 1   1   32    1    B   65 164 24.16716
## 2   2   34    1    A   47 172 15.88697
## 3   3   43    1    B   80 168 28.34467
## 4   4   35    1    A   63 167 22.58955
## 5   5   36    2    C   63 162 24.00549
## 6   6   44    1    C   80 170 27.68166
## 7   7   37    1    B   67 164 24.91077
## 8   8   29    2    C   58 157 23.53037
## 9   9   32    1    A   72 167 25.81663
## 10 10   33    1    B   69 177 22.02432
## 11 11   41    2    B   70 165 25.71166
## 12 12   37    2    C   74 175 24.16327
## 13 13   37    2    B   66 157 26.77593
## 14 14   36    1    A   76 170 26.29758
## 15 15   32    2    C   68 174 22.46003
## 16 16   44    2    C   73 172 24.67550
## 17 17   37    2    C   81 171 27.70083
## 18 18   25    1    B   74 165 27.18090
## 19 19   39    2    B   67 163 25.21736
## 20 20   33    1    C   81 162 30.86420
## 21 21   30    1    A   80 171 27.35885
## 22 22   34    2    A   75 162 28.57796
## 23 23   30    1    C   72 166 26.12861
## 24 24   31    1    B   64 168 22.67574
## 25 25   32    2    B   84 185 24.54346
## 26 26   27    2    B   64 165 23.50781
## 27 27   39    2    B   92 172 31.09789
## 28 28   36    1    B   85 171 29.06877
## 29 29   29    2    B   68 162 25.91068
## 30 30   41    2    C   60 169 21.00767

Para crear dos conjuntos de datos diferenciados para hombres y mujeres:

Df_Mujeres <- Midataf[Midataf$Gene == 1,]
Df_Mujeres
##    Id Edad Gene Trat Peso Alt      IMC
## 1   1   32    1    B   65 164 24.16716
## 2   2   34    1    A   47 172 15.88697
## 3   3   43    1    B   80 168 28.34467
## 4   4   35    1    A   63 167 22.58955
## 6   6   44    1    C   80 170 27.68166
## 7   7   37    1    B   67 164 24.91077
## 9   9   32    1    A   72 167 25.81663
## 10 10   33    1    B   69 177 22.02432
## 14 14   36    1    A   76 170 26.29758
## 18 18   25    1    B   74 165 27.18090
## 20 20   33    1    C   81 162 30.86420
## 21 21   30    1    A   80 171 27.35885
## 23 23   30    1    C   72 166 26.12861
## 24 24   31    1    B   64 168 22.67574
## 28 28   36    1    B   85 171 29.06877
Df_Hombres <- Midataf[Midataf$Gene == 2,]
Df_Hombres
##    Id Edad Gene Trat Peso Alt      IMC
## 5   5   36    2    C   63 162 24.00549
## 8   8   29    2    C   58 157 23.53037
## 11 11   41    2    B   70 165 25.71166
## 12 12   37    2    C   74 175 24.16327
## 13 13   37    2    B   66 157 26.77593
## 15 15   32    2    C   68 174 22.46003
## 16 16   44    2    C   73 172 24.67550
## 17 17   37    2    C   81 171 27.70083
## 19 19   39    2    B   67 163 25.21736
## 22 22   34    2    A   75 162 28.57796
## 25 25   32    2    B   84 185 24.54346
## 26 26   27    2    B   64 165 23.50781
## 27 27   39    2    B   92 172 31.09789
## 29 29   29    2    B   68 162 25.91068
## 30 30   41    2    C   60 169 21.00767

Para usar el comando rbind() y combinar los ficheros creados anteriormente:

Midataf_ordenado <- rbind(Df_Mujeres, Df_Hombres)
Midataf_ordenado
##    Id Edad Gene Trat Peso Alt      IMC
## 1   1   32    1    B   65 164 24.16716
## 2   2   34    1    A   47 172 15.88697
## 3   3   43    1    B   80 168 28.34467
## 4   4   35    1    A   63 167 22.58955
## 6   6   44    1    C   80 170 27.68166
## 7   7   37    1    B   67 164 24.91077
## 9   9   32    1    A   72 167 25.81663
## 10 10   33    1    B   69 177 22.02432
## 14 14   36    1    A   76 170 26.29758
## 18 18   25    1    B   74 165 27.18090
## 20 20   33    1    C   81 162 30.86420
## 21 21   30    1    A   80 171 27.35885
## 23 23   30    1    C   72 166 26.12861
## 24 24   31    1    B   64 168 22.67574
## 28 28   36    1    B   85 171 29.06877
## 5   5   36    2    C   63 162 24.00549
## 8   8   29    2    C   58 157 23.53037
## 11 11   41    2    B   70 165 25.71166
## 12 12   37    2    C   74 175 24.16327
## 13 13   37    2    B   66 157 26.77593
## 15 15   32    2    C   68 174 22.46003
## 16 16   44    2    C   73 172 24.67550
## 17 17   37    2    C   81 171 27.70083
## 19 19   39    2    B   67 163 25.21736
## 22 22   34    2    A   75 162 28.57796
## 25 25   32    2    B   84 185 24.54346
## 26 26   27    2    B   64 165 23.50781
## 27 27   39    2    B   92 172 31.09789
## 29 29   29    2    B   68 162 25.91068
## 30 30   41    2    C   60 169 21.00767