Ejercicios LAB2

Ejercicio 1:

data("iris","Orange")

summary(iris)
##   Sepal.Length    Sepal.Width     Petal.Length    Petal.Width   
##  Min.   :4.300   Min.   :2.000   Min.   :1.000   Min.   :0.100  
##  1st Qu.:5.100   1st Qu.:2.800   1st Qu.:1.600   1st Qu.:0.300  
##  Median :5.800   Median :3.000   Median :4.350   Median :1.300  
##  Mean   :5.843   Mean   :3.057   Mean   :3.758   Mean   :1.199  
##  3rd Qu.:6.400   3rd Qu.:3.300   3rd Qu.:5.100   3rd Qu.:1.800  
##  Max.   :7.900   Max.   :4.400   Max.   :6.900   Max.   :2.500  
##        Species  
##  setosa    :50  
##  versicolor:50  
##  virginica :50  
##                 
##                 
## 
summary(Orange)
##  Tree       age         circumference  
##  3:7   Min.   : 118.0   Min.   : 30.0  
##  1:7   1st Qu.: 484.0   1st Qu.: 65.5  
##  5:7   Median :1004.0   Median :115.0  
##  2:7   Mean   : 922.1   Mean   :115.9  
##  4:7   3rd Qu.:1372.0   3rd Qu.:161.5  
##        Max.   :1582.0   Max.   :214.0
#table(iris) --> el resultado no aporta información
#prop.table(iris) --> da error
#str(iris) --> viendo la estructura de datos tiene sentido la tabla de frecuencias para Species.
frec<-table(iris$Species)
frec
## 
##     setosa versicolor  virginica 
##         50         50         50
prop.table(frec)
## 
##     setosa versicolor  virginica 
##  0.3333333  0.3333333  0.3333333
table(Orange)
## , , circumference = 30
## 
##     age
## Tree 118 484 664 1004 1231 1372 1582
##    3   1   0   0    0    0    0    0
##    1   1   0   0    0    0    0    0
##    5   1   0   0    0    0    0    0
##    2   0   0   0    0    0    0    0
##    4   0   0   0    0    0    0    0
## 
## , , circumference = 32
## 
##     age
## Tree 118 484 664 1004 1231 1372 1582
##    3   0   0   0    0    0    0    0
##    1   0   0   0    0    0    0    0
##    5   0   0   0    0    0    0    0
##    2   0   0   0    0    0    0    0
##    4   1   0   0    0    0    0    0
## 
## , , circumference = 33
## 
##     age
## Tree 118 484 664 1004 1231 1372 1582
##    3   0   0   0    0    0    0    0
##    1   0   0   0    0    0    0    0
##    5   0   0   0    0    0    0    0
##    2   1   0   0    0    0    0    0
##    4   0   0   0    0    0    0    0
## 
## , , circumference = 49
## 
##     age
## Tree 118 484 664 1004 1231 1372 1582
##    3   0   0   0    0    0    0    0
##    1   0   0   0    0    0    0    0
##    5   0   1   0    0    0    0    0
##    2   0   0   0    0    0    0    0
##    4   0   0   0    0    0    0    0
## 
## , , circumference = 51
## 
##     age
## Tree 118 484 664 1004 1231 1372 1582
##    3   0   1   0    0    0    0    0
##    1   0   0   0    0    0    0    0
##    5   0   0   0    0    0    0    0
##    2   0   0   0    0    0    0    0
##    4   0   0   0    0    0    0    0
## 
## , , circumference = 58
## 
##     age
## Tree 118 484 664 1004 1231 1372 1582
##    3   0   0   0    0    0    0    0
##    1   0   1   0    0    0    0    0
##    5   0   0   0    0    0    0    0
##    2   0   0   0    0    0    0    0
##    4   0   0   0    0    0    0    0
## 
## , , circumference = 62
## 
##     age
## Tree 118 484 664 1004 1231 1372 1582
##    3   0   0   0    0    0    0    0
##    1   0   0   0    0    0    0    0
##    5   0   0   0    0    0    0    0
##    2   0   0   0    0    0    0    0
##    4   0   1   0    0    0    0    0
## 
## , , circumference = 69
## 
##     age
## Tree 118 484 664 1004 1231 1372 1582
##    3   0   0   0    0    0    0    0
##    1   0   0   0    0    0    0    0
##    5   0   0   0    0    0    0    0
##    2   0   1   0    0    0    0    0
##    4   0   0   0    0    0    0    0
## 
## , , circumference = 75
## 
##     age
## Tree 118 484 664 1004 1231 1372 1582
##    3   0   0   1    0    0    0    0
##    1   0   0   0    0    0    0    0
##    5   0   0   0    0    0    0    0
##    2   0   0   0    0    0    0    0
##    4   0   0   0    0    0    0    0
## 
## , , circumference = 81
## 
##     age
## Tree 118 484 664 1004 1231 1372 1582
##    3   0   0   0    0    0    0    0
##    1   0   0   0    0    0    0    0
##    5   0   0   1    0    0    0    0
##    2   0   0   0    0    0    0    0
##    4   0   0   0    0    0    0    0
## 
## , , circumference = 87
## 
##     age
## Tree 118 484 664 1004 1231 1372 1582
##    3   0   0   0    0    0    0    0
##    1   0   0   1    0    0    0    0
##    5   0   0   0    0    0    0    0
##    2   0   0   0    0    0    0    0
##    4   0   0   0    0    0    0    0
## 
## , , circumference = 108
## 
##     age
## Tree 118 484 664 1004 1231 1372 1582
##    3   0   0   0    1    0    0    0
##    1   0   0   0    0    0    0    0
##    5   0   0   0    0    0    0    0
##    2   0   0   0    0    0    0    0
##    4   0   0   0    0    0    0    0
## 
## , , circumference = 111
## 
##     age
## Tree 118 484 664 1004 1231 1372 1582
##    3   0   0   0    0    0    0    0
##    1   0   0   0    0    0    0    0
##    5   0   0   0    0    0    0    0
##    2   0   0   1    0    0    0    0
##    4   0   0   0    0    0    0    0
## 
## , , circumference = 112
## 
##     age
## Tree 118 484 664 1004 1231 1372 1582
##    3   0   0   0    0    0    0    0
##    1   0   0   0    0    0    0    0
##    5   0   0   0    0    0    0    0
##    2   0   0   0    0    0    0    0
##    4   0   0   1    0    0    0    0
## 
## , , circumference = 115
## 
##     age
## Tree 118 484 664 1004 1231 1372 1582
##    3   0   0   0    0    1    0    0
##    1   0   0   0    1    0    0    0
##    5   0   0   0    0    0    0    0
##    2   0   0   0    0    0    0    0
##    4   0   0   0    0    0    0    0
## 
## , , circumference = 120
## 
##     age
## Tree 118 484 664 1004 1231 1372 1582
##    3   0   0   0    0    0    0    0
##    1   0   0   0    0    1    0    0
##    5   0   0   0    0    0    0    0
##    2   0   0   0    0    0    0    0
##    4   0   0   0    0    0    0    0
## 
## , , circumference = 125
## 
##     age
## Tree 118 484 664 1004 1231 1372 1582
##    3   0   0   0    0    0    0    0
##    1   0   0   0    0    0    0    0
##    5   0   0   0    1    0    0    0
##    2   0   0   0    0    0    0    0
##    4   0   0   0    0    0    0    0
## 
## , , circumference = 139
## 
##     age
## Tree 118 484 664 1004 1231 1372 1582
##    3   0   0   0    0    0    1    0
##    1   0   0   0    0    0    0    0
##    5   0   0   0    0    0    0    0
##    2   0   0   0    0    0    0    0
##    4   0   0   0    0    0    0    0
## 
## , , circumference = 140
## 
##     age
## Tree 118 484 664 1004 1231 1372 1582
##    3   0   0   0    0    0    0    1
##    1   0   0   0    0    0    0    0
##    5   0   0   0    0    0    0    0
##    2   0   0   0    0    0    0    0
##    4   0   0   0    0    0    0    0
## 
## , , circumference = 142
## 
##     age
## Tree 118 484 664 1004 1231 1372 1582
##    3   0   0   0    0    0    0    0
##    1   0   0   0    0    0    1    0
##    5   0   0   0    0    1    0    0
##    2   0   0   0    0    0    0    0
##    4   0   0   0    0    0    0    0
## 
## , , circumference = 145
## 
##     age
## Tree 118 484 664 1004 1231 1372 1582
##    3   0   0   0    0    0    0    0
##    1   0   0   0    0    0    0    1
##    5   0   0   0    0    0    0    0
##    2   0   0   0    0    0    0    0
##    4   0   0   0    0    0    0    0
## 
## , , circumference = 156
## 
##     age
## Tree 118 484 664 1004 1231 1372 1582
##    3   0   0   0    0    0    0    0
##    1   0   0   0    0    0    0    0
##    5   0   0   0    0    0    0    0
##    2   0   0   0    1    0    0    0
##    4   0   0   0    0    0    0    0
## 
## , , circumference = 167
## 
##     age
## Tree 118 484 664 1004 1231 1372 1582
##    3   0   0   0    0    0    0    0
##    1   0   0   0    0    0    0    0
##    5   0   0   0    0    0    0    0
##    2   0   0   0    0    0    0    0
##    4   0   0   0    1    0    0    0
## 
## , , circumference = 172
## 
##     age
## Tree 118 484 664 1004 1231 1372 1582
##    3   0   0   0    0    0    0    0
##    1   0   0   0    0    0    0    0
##    5   0   0   0    0    0    0    0
##    2   0   0   0    0    1    0    0
##    4   0   0   0    0    0    0    0
## 
## , , circumference = 174
## 
##     age
## Tree 118 484 664 1004 1231 1372 1582
##    3   0   0   0    0    0    0    0
##    1   0   0   0    0    0    0    0
##    5   0   0   0    0    0    1    0
##    2   0   0   0    0    0    0    0
##    4   0   0   0    0    0    0    0
## 
## , , circumference = 177
## 
##     age
## Tree 118 484 664 1004 1231 1372 1582
##    3   0   0   0    0    0    0    0
##    1   0   0   0    0    0    0    0
##    5   0   0   0    0    0    0    1
##    2   0   0   0    0    0    0    0
##    4   0   0   0    0    0    0    0
## 
## , , circumference = 179
## 
##     age
## Tree 118 484 664 1004 1231 1372 1582
##    3   0   0   0    0    0    0    0
##    1   0   0   0    0    0    0    0
##    5   0   0   0    0    0    0    0
##    2   0   0   0    0    0    0    0
##    4   0   0   0    0    1    0    0
## 
## , , circumference = 203
## 
##     age
## Tree 118 484 664 1004 1231 1372 1582
##    3   0   0   0    0    0    0    0
##    1   0   0   0    0    0    0    0
##    5   0   0   0    0    0    0    0
##    2   0   0   0    0    0    1    1
##    4   0   0   0    0    0    0    0
## 
## , , circumference = 209
## 
##     age
## Tree 118 484 664 1004 1231 1372 1582
##    3   0   0   0    0    0    0    0
##    1   0   0   0    0    0    0    0
##    5   0   0   0    0    0    0    0
##    2   0   0   0    0    0    0    0
##    4   0   0   0    0    0    1    0
## 
## , , circumference = 214
## 
##     age
## Tree 118 484 664 1004 1231 1372 1582
##    3   0   0   0    0    0    0    0
##    1   0   0   0    0    0    0    0
##    5   0   0   0    0    0    0    0
##    2   0   0   0    0    0    0    0
##    4   0   0   0    0    0    0    1
#View(Orange)
#no tiene sentido hacer la tabla usando todo el conjunto porque utiliza la variable circunferencia como categoria y hay un exceso de categorias.
library(knitr)
attach(Orange)
kable(table(age,Tree))
3 1 5 2 4
118 1 1 1 1 1
484 1 1 1 1 1
664 1 1 1 1 1
1004 1 1 1 1 1
1231 1 1 1 1 1
1372 1 1 1 1 1
1582 1 1 1 1 1
detach(Orange)

Ejercicio 2:

vect1 <- c(1,2,1,2,1,2,1,2,1,2,1,1,1,1,2,2,1,1,2,1)
vect2 <- c(1,1,2,2,2,1,2,1,1,2,1,2,1,1,1,2,1,1,1,1)

Responded a los apartados siguientes:

vect1 <- c(1,2,1,2,1,2,1,2,1,2,1,1,1,1,2,2,1,1,2,1)
Bajo_peso<-factor(x=vect1, levels=c(1,2), labels=c("Bajo peso","Peso normal"))
Bajo_peso
##  [1] Bajo peso   Peso normal Bajo peso   Peso normal Bajo peso   Peso normal
##  [7] Bajo peso   Peso normal Bajo peso   Peso normal Bajo peso   Bajo peso  
## [13] Bajo peso   Bajo peso   Peso normal Peso normal Bajo peso   Bajo peso  
## [19] Peso normal Bajo peso  
## Levels: Bajo peso Peso normal
vect2 <- c(1,1,2,2,2,1,2,1,1,2,1,2,1,1,1,2,1,1,1,1)
Fumador<-factor(x=vect2, levels=c(1,2), labels=c("Fuma","No fuma"))
Fumador
##  [1] Fuma    Fuma    No fuma No fuma No fuma Fuma    No fuma Fuma    Fuma   
## [10] No fuma Fuma    No fuma Fuma    Fuma    Fuma    No fuma Fuma    Fuma   
## [19] Fuma    Fuma   
## Levels: Fuma No fuma
library(knitr)
vect1 <- c(1,2,1,2,1,2,1,2,1,2,1,1,1,1,2,2,1,1,2,1)
Bajo_peso<-factor(x=vect1, levels=c(1,2), labels=c("Bajo peso","Peso normal"))
vect2 <- c(1,1,2,2,2,1,2,1,1,2,1,2,1,1,1,2,1,1,1,1)
Fumador<-factor(x=vect2, levels=c(1,2), labels=c("Fuma","No fuma"))
Fumador
##  [1] Fuma    Fuma    No fuma No fuma No fuma Fuma    No fuma Fuma    Fuma   
## [10] No fuma Fuma    No fuma Fuma    Fuma    Fuma    No fuma Fuma    Fuma   
## [19] Fuma    Fuma   
## Levels: Fuma No fuma
#--------C-------
tabla<-table(Bajo_peso,Fumador)
kable(tabla)
Fuma No fuma
Bajo peso 8 4
Peso normal 5 3
#------D--------
chisq.test(tabla)
## Warning in chisq.test(tabla): Chi-squared approximation may be incorrect
## 
##  Pearson's Chi-squared test with Yates' continuity correction
## 
## data:  tabla
## X-squared = 0, df = 1, p-value = 1
#------E-------
fisher.test(tabla)
## 
##  Fisher's Exact Test for Count Data
## 
## data:  tabla
## p-value = 1
## alternative hypothesis: true odds ratio is not equal to 1
## 95 percent confidence interval:
##   0.1200513 10.9278345
## sample estimates:
## odds ratio 
##   1.189031
#no hay una asociacion clara entre las variables

Ejercicio 3:

  1. Activad el paquete de datos airquality del paquete datasets y generad los siguientes gráficos:
    • Un gráfico de dispersión de la variable Ozone de color azul y con almohadillas (#) en vez de puntos.
    • Un gráfico de caja de color rojo con la variable Temp con el título Temperatura (en grados Farenheit).
  2. Activad el paquete de datos airmiles del paquete datasets y generad los siguientes gráficos:
    • Un gráfico de líneas de la serie de datos airmiles con el título Datos de pasajeros en vuelos comerciales (en miles) y de color azul (cadetblue2) y la etiqueta del eje x con Miles de pasajeros.
    • Un histograma de la serie de datos airmiles de color marrón (chocolate2).
  3. Representad los cuatro gráficos en una única imagen donde los veamos juntos.
data(airquality)
data(airmiles)
par(mfrow=c(2,2)) # apartado C
#-----A.1----
#head(airquality)
plot(airquality$Ozone, col="blue", pch="#")

#----A.2------
plot(airquality$Temp, col="red", main="Temperatura (en
grados Farenheit)")

#---B.1------
plot(airmiles, 
     main="Datos de pasajeros en
     vuelos comerciales(en miles)",
     col="cadetblue2",
     xlab="Miles de pasajeros")

#---B.2----
hist(airmiles, col="chocolate2")

Ejercicio 4:

set.seed(354)
x1<-sample(18:85, 60)
y1<-x1/6+ rnorm(60)

par(mfrow=c(2,2))
plot(x1,y1, main="Gráfico de dispersión")
abline(lm(y1~x1), col="cadetblue3")
plot(x1^2,y1, main="G. dispersión X^2")
plot(density(x1),main="Densidad X",col="chocolate2", lwd=3)
plot(density(y1),main="Densidad Y",col="aquamarine", lwd=3)

Ejercicio 5:

Para poder practicar la creación de gráficos con ggplot2, vamos a crear seis gráficos con diferentes características y con diferentes conjuntos de datos de paquetes trabajados anteriormente.

# Cargar librería
library(ggplot2)
library(dplyr)
## 
## Attaching package: 'dplyr'
## The following objects are masked from 'package:stats':
## 
##     filter, lag
## The following objects are masked from 'package:base':
## 
##     intersect, setdiff, setequal, union
library("MASS")
## 
## Attaching package: 'MASS'
## The following object is masked from 'package:dplyr':
## 
##     select
data("birthwt")
#head(airquality)

#-----A-----
par(mfrow=c(2,2))

ggplot(data=airquality, aes(x=Solar.R,y=Temp)) +
  geom_point() +
  geom_smooth(method="lm", col="darkred")
## `geom_smooth()` using formula = 'y ~ x'
## Warning: Removed 7 rows containing non-finite outside the scale range
## (`stat_smooth()`).
## Warning: Removed 7 rows containing missing values or values outside the scale range
## (`geom_point()`).

#----B------
ggplot(
  data=airquality, 
  aes(
    Solar.R,Temp,as.factor, 
    col=factor(Month), 
    shape=factor(Month)
    )
  ) +
  geom_point()
## Warning: Removed 7 rows containing missing values or values outside the scale range
## (`geom_point()`).

#----C----
ggplot(data=birthwt, aes(age))+
  geom_histogram(fill="blue", colour="black")
## `stat_bin()` using `bins = 30`. Pick better value `binwidth`.

#---D----
ggplot(birthwt,aes(age)) +
geom_histogram(binwidth=5, fill="violet",col="black")+
facet_grid(~smoke)

Ejercicio 6:

Cread un gráfico con unos datos extraídos del paquete Datasets de R y guardadlo como imagen (.jpg) con el nombre migrafic1 y, también, como documento en PDF con el nombre migrafic2. Haced una captura de pantalla del fichero generado.

#View(HairEyeColor)
#str(HairEyeColor)
datos <- as.data.frame(HairEyeColor)
#?aggregate 
#uso aggregate() del ejemplo 10
datos_freq <- aggregate(Freq ~ (Hair + Sex), data = datos, sum)
#variable Freq agrupada en funcion de Hair y Sex, sum da la frecuencia total
datos_freq
library(ggplot2)
#??ggplot2
cabello<-ggplot(datos_freq, aes(x = Hair, y = Freq)) +
  geom_col() +      
  facet_grid(~Sex)                  
 
jpeg("migrafic1.jpg")
cabello
dev.off()
## png 
##   2
#file.show("migrafic1.jpg")

pdf("migrafic2.pdf")
cabello
dev.off()
## png 
##   2
#file.show("migrafic2.pdf")

EJercicio 7: Para practicar la regresión lineal simple usaremos el conjunto de datos Orange que se encuentra en la librería tidyverse y que tiene información sobre tres variables (árbol, edad en días desde que se sembró el árbol y circunferencia del tronco en centímetros) de 35 naranjos.

head(Orange)
summary(Orange)
##  Tree       age         circumference  
##  3:7   Min.   : 118.0   Min.   : 30.0  
##  1:7   1st Qu.: 484.0   1st Qu.: 65.5  
##  5:7   Median :1004.0   Median :115.0  
##  2:7   Mean   : 922.1   Mean   :115.9  
##  4:7   3rd Qu.:1372.0   3rd Qu.:161.5  
##        Max.   :1582.0   Max.   :214.0
pairs(Orange)

cor(Orange$age,Orange$circumference, method = "pearson")
## [1] 0.9135189
#hay correlación
model<-lm(circumference ~ age, data=Orange)
plot(Orange$age,Orange$circumference, xlab="Edad", ylab="Circunferencia")
abline(model) #se ajusta

residuos <-rstandard(model)
val.ajust<-fitted(model)
plot(val.ajust,residuos) #no hay patrón

qqnorm(residuos)
qqline(residuos)

#circunferencia arbol 600 dias después
c600<-data.frame(age=600)
predict(model,c600)
##        1 
## 81.46185
#el valor de circunferencia a los 600 día será 81.46 aprox.


#-------------------------------EJERCICIO 8------------------------------

library(ggplot2)
#dispersión
ggplot(Orange, aes(age,circumference))+
  geom_point()+
  geom_smooth(method="lm")
## `geom_smooth()` using formula = 'y ~ x'

#residuos
df_res<-data.frame(val.ajust, residuos)
ggplot(df_res, aes(sample=residuos))+
  stat_qq()+
  stat_qq_line()

Ejercicio 9: Activad el conjunto de datos PlantGrowth del paquete datasets de R. Este archivo tiene los recultados de un experimento para comparar los rendimientos medios por el peso seco de las plantas (weight) obtenidos bajo un control y dos condiciones de tratamiento diferentes (group factor).

data(PlantGrowth)
#install.packages("rapportools") en consola
library("rapportools")
## 
## Attaching package: 'rapportools'
## The following object is masked from 'package:dplyr':
## 
##     n
## The following objects are masked from 'package:stats':
## 
##     IQR, median, sd, var
## The following objects are masked from 'package:base':
## 
##     max, mean, min, range, sum
#View(PlantGrowth)
tapply(PlantGrowth$weight, PlantGrowth$group, mean) #diferencias no tan claras
##  ctrl  trt1  trt2 
## 5.032 4.661 5.526
boxplot(weight ~ group, data = PlantGrowth, col=palette.colors())

#APARTADO 1: se observan diferencias más claras al hacer un boxplot.

#APARTADO 2
x<-rp.outlier(PlantGrowth$weight[PlantGrowth$group=="trt1"])

#no existen valores outliers
grupo<-as.numeric(PlantGrowth$group)

by(PlantGrowth$weight,grupo, shapiro.test)
## grupo: 1
## 
##  Shapiro-Wilk normality test
## 
## data:  dd[x, ]
## W = 0.95668, p-value = 0.7475
## 
## ------------------------------------------------------------ 
## grupo: 2
## 
##  Shapiro-Wilk normality test
## 
## data:  dd[x, ]
## W = 0.93041, p-value = 0.4519
## 
## ------------------------------------------------------------ 
## grupo: 3
## 
##  Shapiro-Wilk normality test
## 
## data:  dd[x, ]
## W = 0.94101, p-value = 0.5643
bartlett.test(PlantGrowth$weight,grupo)
## 
##  Bartlett test of homogeneity of variances
## 
## data:  PlantGrowth$weight and grupo
## Bartlett's K-squared = 2.8786, df = 2, p-value = 0.2371
#p > 0.05 en todos los casos, los datos son normales y de variaza homogénea. Sí se cumplen las condiciones para aplicar un ANOVA.

Ejercicio 10: Buscad información del paquete Plotly para la creación de gráficos interactivos y generad un histograma o un gráfico de barras interactivo. Explicad qué se puede hacer con este gráfico.

Ref: https://plotly.com/ggplot2/histograms/

library(plotly)
## 
## Attaching package: 'plotly'
## The following object is masked from 'package:MASS':
## 
##     select
## 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(ggplot2)
aves<-as.integer(runif(10,1,20))
CA<-c("Andalucía", "Asturias", "Baleares", "Canarias","Catalunya", "Catilla y León", "Extremadura", "Galicia", "Valencia", "País Vasco")
aves_c<-data.frame("Comunidades"=CA,"Aves autóctonas"=aves)

graph<-ggplot(aves_c, aes(CA, aves, col=CA, fill=CA))+
  geom_col()+
  labs(y="No. aves autóct./CA")

ggplotly(graph) #podemos ver el número de especies autóctonas de aves de cada comunidad, también podemos seleccionar solo aquellas comunidades que queremos comparar con box select o pinchando las casillas de la leyenda. 

Caso práctico

Caso práctico

A partir de unos datos bioclínicos o biosanitarios que escojáis y que importéis a R, explicad sus variables (mínimo de ocho variables) y también:

Respuesta:

  1. Obtuve el dataset de: IHME

  2. Seleccioné los datos de obesidad desde los 5 años a los 24 (tabla OB)

  3. Elegí las siguientes variables (teniendo en cuenta solo los datos reales y no los extrapolados):

    • Sex
    • age_group_name (rango de edad)
    • year_id (año)
    • mean_prev (media de prevalencia de sobrepeso por rango de edad)
    • lower_prev (percentil 2.5% de ese rango)
    • upper_prev(percentil 97,5% de ese rango)
    • mean_change(porcentaje medio de cambio desde 1990-2021)
    • lower_change (percentil 2.5% de mean_change)
    • upper_change (percentil 95,5% de mean_change)

tapply(final$mean_prev, final$year_id, mean)

library(readr)
dataset<- read_csv("C:/UOC_BI/PRIMER_SEMESTRE/S_A_D/RETO_1/LAB2/obesity/obesity.CSV")
## Rows: 170556 Columns: 15
## ── Column specification ────────────────────────────────────────────────────────
## Delimiter: ","
## chr  (5): metric, location_level, location_name, Sex, age_group_name
## dbl (10): location_id, sex_id, age_group_id, year_id, mean_prev, lower_prev,...
## 
## ℹ Use `spec()` to retrieve the full column specification for this data.
## ℹ Specify the column types or set `show_col_types = FALSE` to quiet this message.
head(dataset[5:14])
selec<-subset(dataset,select=c(Sex,age_group_name,year_id,mean_prev,lower_prev,upper_prev, mean_change, lower_change, upper_change))
#length(subset)

final<-selec[selec$year_id<=2021,] #seleccionamos solo los datos reales.
head(final)
#########################    APARTADO 1    ###############################
#en este caso no tiene sentido hacer un summary porque los datos vienen resumidos

#---------------media de prevalencia total por año---------------
prev_total<-aggregate(mean_prev ~ year_id, data=final, mean)

#2.5%
prev_total_lower<-aggregate(lower_prev ~ year_id, data=final, mean)
#95.5%
prev_total_upper<-aggregate(upper_prev ~ year_id, data=final, mean)
 
#----------media de prevalencia total por año y cohorte-------------
#str(final$age_group_name)

poredad<-aggregate(mean_prev ~ 
            year_id+
            as.numeric(factor(final$age_group_name)), 
          data=final, mean) 
#2.5%
poredad_lower<-aggregate(lower_prev ~ 
            year_id+
            as.numeric(factor(final$age_group_name)), 
          data=final, mean)
#95.5%
poredad_upper<-aggregate(upper_prev ~ 
            year_id+
            as.numeric(factor(final$age_group_name)), 
          data=final, mean)

#----------porcentaje cambio 1990-2021 por rango de edad y sexo------------
cambio<-aggregate(mean_change ~ Sex+
            as.numeric(factor(final$age_group_name)), 
          data=final, mean)

#2.5%
cambio_lower<-aggregate(lower_change ~ Sex+
            as.numeric(factor(final$age_group_name)), 
          data=final, mean)
#95.5%
cambio_lower<-aggregate(upper_change ~ Sex+
            as.numeric(factor(final$age_group_name)), 
          data=final, mean)

#########################    APARTADO 2    ###############################
#gráfico1
plot(prev_total, type="line", main="Media total de prevalencia", col="red", lwd=3, xlab="year", ylab="Prevalencia media") 
## Warning in plot.xy(xy, type, ...): plot type 'line' will be truncated to first
## character

#aumento progresivo de prevalencia desde 1990

#gráfico2
plot(prev_total, type="line", main="Media total de prevalencia", col="red", lwd=10, xlab="year", ylab="Prevalencia media")
## Warning in plot.xy(xy, type, ...): plot type 'line' will be truncated to first
## character
lines(prev_total_upper,col="orange", lwd=10)
lines(prev_total_lower,col="blue", lwd=10)

abline(lm(prev_total_upper$upper_prev~prev_total_upper$year_id))
abline(lm(prev_total$mean_prev~prev_total$year_id))
abline(lm(prev_total_lower$lower_prev~prev_total_lower$year_id))