R Markdown

This is an R Markdown document. Markdown is a simple formatting syntax for authoring HTML, PDF, and MS Word documents. For more details on using R Markdown see http://rmarkdown.rstudio.com.

When you click the Knit button a document will be generated that includes both content as well as the output of any embedded R code chunks within the document. You can embed an R code chunk like this:

#apartado a)
library(datasets)
library(knitr)
data(Orange)
head(Orange)
##   Tree  age circumference
## 1    1  118            30
## 2    1  484            58
## 3    1  664            87
## 4    1 1004           115
## 5    1 1231           120
## 6    1 1372           142
## Tree age circumference
## 1 1 118 30
## 2 1 484 58
## 3 1 664 87
## 4 1 1004 115
## 5 1 1231 120
## 6 1 1372 142
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
## 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
data(iris)
head(iris)
##   Sepal.Length Sepal.Width Petal.Length Petal.Width Species
## 1          5.1         3.5          1.4         0.2  setosa
## 2          4.9         3.0          1.4         0.2  setosa
## 3          4.7         3.2          1.3         0.2  setosa
## 4          4.6         3.1          1.5         0.2  setosa
## 5          5.0         3.6          1.4         0.2  setosa
## 6          5.4         3.9          1.7         0.4  setosa
## Sepal.Length Sepal.Width Petal.Length Petal.Width Species
## 1 5.1 3.5 1.4 0.2 setosa
## 2 4.9 3.0 1.4 0.2 setosa
## 3 4.7 3.2 1.3 0.2 setosa
## 4 4.6 3.1 1.5 0.2 setosa
## 5 5.0 3.6 1.4 0.2 setosa
## 6 5.4 3.9 1.7 0.4 setosa
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  
##                 
##                 
## 
## 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 
##
##
## 
#apartado b)
#frecuencias relativas variables iris
kable(prop.table(iris$Sepal.Length))
x
0.0058186
0.0055904
0.0053622
0.0052481
0.0057045
0.0061609
0.0052481
0.0057045
0.0050200
0.0055904
0.0061609
0.0054763
0.0054763
0.0049059
0.0066172
0.0065031
0.0061609
0.0058186
0.0065031
0.0058186
0.0061609
0.0058186
0.0052481
0.0058186
0.0054763
0.0057045
0.0057045
0.0059327
0.0059327
0.0053622
0.0054763
0.0061609
0.0059327
0.0062750
0.0055904
0.0057045
0.0062750
0.0055904
0.0050200
0.0058186
0.0057045
0.0051341
0.0050200
0.0057045
0.0058186
0.0054763
0.0058186
0.0052481
0.0060468
0.0057045
0.0079863
0.0073018
0.0078722
0.0062750
0.0074159
0.0065031
0.0071877
0.0055904
0.0075299
0.0059327
0.0057045
0.0067313
0.0068454
0.0069595
0.0063890
0.0076440
0.0063890
0.0066172
0.0070736
0.0063890
0.0067313
0.0069595
0.0071877
0.0069595
0.0073018
0.0075299
0.0077581
0.0076440
0.0068454
0.0065031
0.0062750
0.0062750
0.0066172
0.0068454
0.0061609
0.0068454
0.0076440
0.0071877
0.0063890
0.0062750
0.0062750
0.0069595
0.0066172
0.0057045
0.0063890
0.0065031
0.0065031
0.0070736
0.0058186
0.0065031
0.0071877
0.0066172
0.0081004
0.0071877
0.0074159
0.0086708
0.0055904
0.0083286
0.0076440
0.0082145
0.0074159
0.0073018
0.0077581
0.0065031
0.0066172
0.0073018
0.0074159
0.0087849
0.0087849
0.0068454
0.0078722
0.0063890
0.0087849
0.0071877
0.0076440
0.0082145
0.0070736
0.0069595
0.0073018
0.0082145
0.0084427
0.0090131
0.0073018
0.0071877
0.0069595
0.0087849
0.0071877
0.0073018
0.0068454
0.0078722
0.0076440
0.0078722
0.0066172
0.0077581
0.0076440
0.0076440
0.0071877
0.0074159
0.0070736
0.0067313
kable(prop.table(iris$Sepal.Width))
x
0.0076319
0.0065416
0.0069778
0.0067597
0.0078500
0.0085041
0.0074139
0.0074139
0.0063236
0.0067597
0.0080680
0.0074139
0.0065416
0.0065416
0.0087222
0.0095944
0.0085041
0.0076319
0.0082861
0.0082861
0.0074139
0.0080680
0.0078500
0.0071958
0.0074139
0.0065416
0.0074139
0.0076319
0.0074139
0.0069778
0.0067597
0.0074139
0.0089403
0.0091583
0.0067597
0.0069778
0.0076319
0.0078500
0.0065416
0.0074139
0.0076319
0.0050153
0.0069778
0.0076319
0.0082861
0.0065416
0.0082861
0.0069778
0.0080680
0.0071958
0.0069778
0.0069778
0.0067597
0.0050153
0.0061055
0.0061055
0.0071958
0.0052333
0.0063236
0.0058875
0.0043611
0.0065416
0.0047972
0.0063236
0.0063236
0.0067597
0.0065416
0.0058875
0.0047972
0.0054514
0.0069778
0.0061055
0.0054514
0.0061055
0.0063236
0.0065416
0.0061055
0.0065416
0.0063236
0.0056694
0.0052333
0.0052333
0.0058875
0.0058875
0.0065416
0.0074139
0.0067597
0.0050153
0.0065416
0.0054514
0.0056694
0.0065416
0.0056694
0.0050153
0.0058875
0.0065416
0.0063236
0.0063236
0.0054514
0.0061055
0.0071958
0.0058875
0.0065416
0.0063236
0.0065416
0.0065416
0.0054514
0.0063236
0.0054514
0.0078500
0.0069778
0.0058875
0.0065416
0.0054514
0.0061055
0.0069778
0.0065416
0.0082861
0.0056694
0.0047972
0.0069778
0.0061055
0.0061055
0.0058875
0.0071958
0.0069778
0.0061055
0.0065416
0.0061055
0.0065416
0.0061055
0.0082861
0.0061055
0.0061055
0.0056694
0.0065416
0.0074139
0.0067597
0.0065416
0.0067597
0.0067597
0.0067597
0.0058875
0.0069778
0.0071958
0.0065416
0.0054514
0.0065416
0.0074139
0.0065416
kable(prop.table(iris$Petal.Length))
x
0.0024836
0.0024836
0.0023062
0.0026610
0.0024836
0.0030158
0.0024836
0.0026610
0.0024836
0.0026610
0.0026610
0.0028384
0.0024836
0.0019514
0.0021288
0.0026610
0.0023062
0.0024836
0.0030158
0.0026610
0.0030158
0.0026610
0.0017740
0.0030158
0.0033706
0.0028384
0.0028384
0.0026610
0.0024836
0.0028384
0.0028384
0.0026610
0.0026610
0.0024836
0.0026610
0.0021288
0.0023062
0.0024836
0.0023062
0.0026610
0.0023062
0.0023062
0.0023062
0.0028384
0.0033706
0.0024836
0.0028384
0.0024836
0.0026610
0.0024836
0.0083378
0.0079830
0.0086926
0.0070960
0.0081604
0.0079830
0.0083378
0.0058542
0.0081604
0.0069186
0.0062090
0.0074508
0.0070960
0.0083378
0.0063864
0.0078056
0.0079830
0.0072734
0.0079830
0.0069186
0.0085152
0.0070960
0.0086926
0.0083378
0.0076282
0.0078056
0.0085152
0.0088700
0.0079830
0.0062090
0.0067412
0.0065638
0.0069186
0.0090474
0.0079830
0.0079830
0.0083378
0.0078056
0.0072734
0.0070960
0.0078056
0.0081604
0.0070960
0.0058542
0.0074508
0.0074508
0.0074508
0.0076282
0.0053220
0.0072734
0.0106440
0.0090474
0.0104666
0.0099344
0.0102892
0.0117084
0.0079830
0.0111762
0.0102892
0.0108214
0.0090474
0.0094022
0.0097570
0.0088700
0.0090474
0.0094022
0.0097570
0.0118858
0.0122406
0.0088700
0.0101118
0.0086926
0.0118858
0.0086926
0.0101118
0.0106440
0.0085152
0.0086926
0.0099344
0.0102892
0.0108214
0.0113536
0.0099344
0.0090474
0.0099344
0.0108214
0.0099344
0.0097570
0.0085152
0.0095796
0.0099344
0.0090474
0.0090474
0.0104666
0.0101118
0.0092248
0.0088700
0.0092248
0.0095796
0.0090474
kable(prop.table(iris$Petal.Width))
x
0.0011117
0.0011117
0.0011117
0.0011117
0.0011117
0.0022235
0.0016676
0.0011117
0.0011117
0.0005559
0.0011117
0.0011117
0.0005559
0.0005559
0.0011117
0.0022235
0.0022235
0.0016676
0.0016676
0.0016676
0.0011117
0.0022235
0.0011117
0.0027793
0.0011117
0.0011117
0.0022235
0.0011117
0.0011117
0.0011117
0.0011117
0.0022235
0.0005559
0.0011117
0.0011117
0.0011117
0.0011117
0.0005559
0.0011117
0.0011117
0.0016676
0.0016676
0.0011117
0.0033352
0.0022235
0.0016676
0.0011117
0.0011117
0.0011117
0.0011117
0.0077821
0.0083380
0.0083380
0.0072262
0.0083380
0.0072262
0.0088938
0.0055586
0.0072262
0.0077821
0.0055586
0.0083380
0.0055586
0.0077821
0.0072262
0.0077821
0.0083380
0.0055586
0.0083380
0.0061145
0.0100056
0.0072262
0.0083380
0.0066704
0.0072262
0.0077821
0.0077821
0.0094497
0.0083380
0.0055586
0.0061145
0.0055586
0.0066704
0.0088938
0.0083380
0.0088938
0.0083380
0.0072262
0.0072262
0.0072262
0.0066704
0.0077821
0.0066704
0.0055586
0.0072262
0.0066704
0.0072262
0.0072262
0.0061145
0.0072262
0.0138966
0.0105614
0.0116732
0.0100056
0.0122290
0.0116732
0.0094497
0.0100056
0.0100056
0.0138966
0.0111173
0.0105614
0.0116732
0.0111173
0.0133407
0.0127849
0.0100056
0.0122290
0.0127849
0.0083380
0.0127849
0.0111173
0.0111173
0.0100056
0.0116732
0.0100056
0.0100056
0.0100056
0.0116732
0.0088938
0.0105614
0.0111173
0.0122290
0.0083380
0.0077821
0.0127849
0.0133407
0.0100056
0.0100056
0.0116732
0.0133407
0.0127849
0.0105614
0.0127849
0.0138966
0.0127849
0.0105614
0.0111173
0.0127849
0.0100056
#kable(prop.table(iris$Species))
#la tabla de frecuencias relativas con Species no es correcta
#apartado c)
kable(table(Orange$Tree))
Var1 Freq
3 7
1 7
5 7
2 7
4 7
kable(table(Orange$age))
Var1 Freq
118 5
484 5
664 5
1004 5
1231 5
1372 5
1582 5
kable(table(Orange$circumference))
Var1 Freq
30 3
32 1
33 1
49 1
51 1
58 1
62 1
69 1
75 1
81 1
87 1
108 1
111 1
112 1
115 2
120 1
125 1
139 1
140 1
142 2
145 1
156 1
167 1
172 1
174 1
177 1
179 1
203 2
209 1
214 1
#la tabla de frecuencias absolutas con la variable Tree no tiene sentido 
#apartado d)
table(Orange$Tree, Orange$age)
##    
##     118 484 664 1004 1231 1372 1582
##   3   1   1   1    1    1    1    1
##   1   1   1   1    1    1    1    1
##   5   1   1   1    1    1    1    1
##   2   1   1   1    1    1    1    1
##   4   1   1   1    1    1    1    1
## 
## 118 484 664 1004 1231 1372 1582
## 3 1 1 1 1 1 1 1
## 1 1 1 1 1 1 1 1
## 5 1 1 1 1 1 1 1
## 2 1 1 1 1 1 1 1
## 4 1 1 1 1 1 1 1
#código del enunciado
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)
#apartado a)
Bajo_Peso=factor(vect1, levels=c(1,2), labels=c("Bajo Peso","Peso Normal")) 
#generamos un factor con sus nuevas etiquetas
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
## [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
#apartado b)
Fumador=factor(vect2, levels=c(1,2), labels=c("Fuma","No Fuma")) #generamos un factor con sus nuevas etiquetas
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
## [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
#apartado c)
tabla<-table(Bajo_Peso,Fumador)
tabla
##              Fumador
## Bajo_Peso     Fuma No Fuma
##   Bajo Peso      8       4
##   Peso Normal    5       3
## Fumador
## Bajo_Peso Fuma No Fuma
## Bajo Peso 8 4
## Peso Normal 5 3
#apartado 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
## 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
#apartado 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
## 
## 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
data("airquality")
data("airmiles")
par(mfrow=c(2,2)) #matriz 2x2
plot(airquality$Ozone, col="blue",pch="#") #apartado a)
boxplot(airquality$Temp, col="red", main="Temperatura (en grados Farenheit)")
plot(airmiles, main = "Datos de pasajeros en vuelos comerciales (miles)",
 xlab = "Miles de pasajeros", col = "cadetblue2")
hist(airmiles, col="chocolate2", main="Histrograma de vuelos comerciales")

set.seed(333)
x1 <- rnorm(500) #simulamos una variable x1
y1 <- x1 + rnorm(500) #simulamos una variable y1 
plot(x1, y1, main="Gráfico de dispersión") #creamos el gráfico de dispersión de las variables
abline(lm(y1~x1), col="orange") #creamos la recta de regresión de color verde

plot(density(x1), main="Densidad de x1", col="aquamarine") #generamos el gráfico de densidad para ver cómo es la distribución
lines(density(y1), col="cadetblue2") #generamos un gráfico con las densidades de las dos variables.

library(ggplot2)
#apartado a)
ggplot(airquality, aes(Solar.R, Temp)) +
 geom_point(size=3) +
 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()`).

## `geom_smooth()` using formula = 'y ~ x'
## Warning: Removed 7 rows containing non-finite values (`stat_smooth()`).
## Warning: Removed 7 rows containing missing values (`geom_point()`).

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

## Warning: Removed 7 rows containing missing values (`geom_point()`).

#apartado c)
library (MASS)
ggplot(birthwt,aes(age)) +
 geom_histogram(binwidth=5, fill="blue",col="black")

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

jpeg("migrafic1.jpg") #abrimos el dispositivo gráfico
data(iris)
boxplot(iris$Petal.Width, col="green")
dev.off #cerramos el dispositivo gráfico
## function (which = dev.cur()) 
## {
##     if (which == 1) 
##         stop("cannot shut down device 1 (the null device)")
##     .External(C_devoff, as.integer(which))
##     dev.cur()
## }
## <bytecode: 0x00000218eb83e8e8>
## <environment: namespace:grDevices>
## function (which = dev.cur()) 
## {
## if (which == 1) 
## stop("cannot shut down device 1 (the null device)")
## .External(C_devoff, as.integer(which))
## dev.cur()
## }
## <bytecode: 0x0000024548da0c38>
## <environment: namespace:grDevices>
pdf("migrafic2.pdf") #abrimos el dispositivo gráfico
data(iris)
boxplot(iris$Petal.Width, col="green")
dev.off #cerramos el dispositivo gráfico
## function (which = dev.cur()) 
## {
##     if (which == 1) 
##         stop("cannot shut down device 1 (the null device)")
##     .External(C_devoff, as.integer(which))
##     dev.cur()
## }
## <bytecode: 0x00000218eb83e8e8>
## <environment: namespace:grDevices>
## function (which = dev.cur()) 
## {
## if (which == 1) 
## stop("cannot shut down device 1 (the null device)")
## .External(C_devoff, as.integer(which))
## dev.cur()
## }
## <bytecode: 0x0000024548da0c38>
## <environment: namespace:grDevices>
#ejercicio de regresión
library(tidyverse)
## ── Attaching core tidyverse packages ──────────────────────── tidyverse 2.0.0 ──
## ✔ dplyr     1.1.4     ✔ readr     2.1.4
## ✔ forcats   1.0.0     ✔ stringr   1.5.1
## ✔ lubridate 1.9.3     ✔ tibble    3.2.1
## ✔ purrr     1.0.2     ✔ tidyr     1.3.0
## ── Conflicts ────────────────────────────────────────── tidyverse_conflicts() ──
## ✖ dplyr::filter() masks stats::filter()
## ✖ dplyr::lag()    masks stats::lag()
## ✖ dplyr::select() masks MASS::select()
## ℹ Use the conflicted package (<http://conflicted.r-lib.org/>) to force all conflicts to become errors
data("Orange")
head(Orange)
## Grouped Data: circumference ~ age | Tree
##   Tree  age circumference
## 1    1  118            30
## 2    1  484            58
## 3    1  664            87
## 4    1 1004           115
## 5    1 1231           120
## 6    1 1372           142
## Grouped Data: circumference ~ age | Tree
## Tree age circumference
## 1 1 118 30
## 2 1 484 58
## 3 1 664 87
## 4 1 1004 115
## 5 1 1231 120
## 6 1 1372 142
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
## 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.test(Orange$age, Orange$circumference)
## 
##  Pearson's product-moment correlation
## 
## data:  Orange$age and Orange$circumference
## t = 12.9, df = 33, p-value = 1.931e-14
## alternative hypothesis: true correlation is not equal to 0
## 95 percent confidence interval:
##  0.8342364 0.9557955
## sample estimates:
##       cor 
## 0.9135189
## 
## Pearson's product-moment correlation
## 
## data: Orange$age and Orange$circumference
## t = 12.9, df = 33, p-value = 1.931e-14
## alternative hypothesis: true correlation is not equal to 0
## 95 percent confidence interval:
## 0.8342364 0.9557955
## sample estimates:
## cor 
## 0.9135189
mod_reg<-lm(circumference ~ age, data = Orange)
summary(mod_reg)
## 
## Call:
## lm(formula = circumference ~ age, data = Orange)
## 
## Residuals:
##     Min      1Q  Median      3Q     Max 
## -46.310 -14.946  -0.076  19.697  45.111 
## 
## Coefficients:
##              Estimate Std. Error t value Pr(>|t|)    
## (Intercept) 17.399650   8.622660   2.018   0.0518 .  
## age          0.106770   0.008277  12.900 1.93e-14 ***
## ---
## Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
## 
## Residual standard error: 23.74 on 33 degrees of freedom
## Multiple R-squared:  0.8345, Adjusted R-squared:  0.8295 
## F-statistic: 166.4 on 1 and 33 DF,  p-value: 1.931e-14
## 
## Call:
## lm(formula = circumference ~ age, data = Orange)
## 
## Residuals:
## Min 1Q Median 3Q Max 
## -46.310 -14.946 -0.076 19.697 45.111 
## 
## Coefficients:
## Estimate Std. Error t value Pr(>|t|) 
## (Intercept) 17.399650 8.622660 2.018 0.0518 . 
## age 0.106770 0.008277 12.900 1.93e-14 ***
## ---
## Signif. codes: 0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
## 
## Residual standard error: 23.74 on 33 degrees of freedom
## Multiple R-squared: 0.8345, Adjusted R-squared: 0.8295 
## F-statistic: 166.4 on 1 and 33 DF, p-value: 1.931e-14
plot(Orange$age,Orange$circumference)
abline(mod_reg)

#estimación
días <- 600
medida <- 0.1068 * días + 17.3997
print(medida)
## [1] 81.4797
## [1] 81.4797
Orange %>%
 ggplot(aes(x = age,
y = circumference)) +
 geom_point() 

Orange %>%
 ggplot(aes(x = age,
y = circumference)) +
 geom_point() +
 geom_abline(intercept = 17.3997,
slope = 0.1068,
col = 'blue') +
 geom_vline(xintercept = 800,
col = 'red')

data("PlantGrowth")
anova(lm(weight ~ group, data = PlantGrowth))
## Analysis of Variance Table
## 
## Response: weight
##           Df  Sum Sq Mean Sq F value  Pr(>F)  
## group      2  3.7663  1.8832  4.8461 0.01591 *
## Residuals 27 10.4921  0.3886                  
## ---
## Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
## Analysis of Variance Table
## 
## Response: weight
## Df Sum Sq Mean Sq F value Pr(>F) 
## group 2 3.7663 1.8832 4.8461 0.01591 *
## Residuals 27 10.4921 0.3886
## ---
## Signif. codes: 0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1

Plotly

# Información   sobre   el  paquete Plotly: https://plotly.com/r/getting-started/
#install.packages("plotly")
#install.packages("gapminder")

##############################
# 1. Preliminaar
##############################

# Emplearemos la siguiente base de datos de la libreria Gapminder:
#   
#  Gapminder con 1704 filas y 6 columnas
# * country = País
# * continent = continente
# * year = año. 
# * lifeExp = esperanza de vida en años.
# * pop = Número de habitantes
# * gdpPercap: Producto Interno Bruto por habitante (PIB per cápita)
library(gapminder)

data("gapminder")

library(ggplot2)

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
##############################
# 2. de ggplot a plotly
##############################

pp <-ggplot(gapminder, aes(x = gdpPercap, y = lifeExp, col = continent)) + 
  geom_jitter() + scale_x_log10()  
pp

ggplotly(pp)
# grabar el gráfico
pp1 <- ggplotly(pp)

htmlwidgets::saveWidget(as_widget(pp1), "mi_grafico.html") 

# Pero ...

pp2 <- ggplot(gapminder, aes(x = gdpPercap, y = lifeExp, shape = continent,  col = as.factor(year))) + 
   geom_jitter() + scale_x_log10()
pp2

ggplotly(pp2)
##############################
# 3. Gráfico directamente en plotly
##############################
g <- plot_ly(gapminder, x = ~gdpPercap, y = ~lifeExp) 
g
## No trace type specified:
##   Based on info supplied, a 'scatter' trace seems appropriate.
##   Read more about this trace type -> https://plotly.com/r/reference/#scatter
## No scatter mode specifed:
##   Setting the mode to markers
##   Read more about this attribute -> https://plotly.com/r/reference/#scatter-mode
g <- add_markers(g)
g
# ahora arreglemos la escala del eje x
g <- layout(g, xaxis = list(type = "log"))
g
# podemos incluir una tercera variable, de manera similiar a la gramática de ggplot


g <- plot_ly(gapminder, x = ~gdpPercap, y = ~lifeExp, color = ~continent) 
g <- add_markers(g)
g <- layout(g, xaxis = list(type = "log"))

g
#¿Para qué pueden servir los gráficos interactivos de plotly de histogramas o barras?
#Un gráfico de barras animado es una excelente opción para visualizar cambios a lo largo del tiempo o comparar diferentes categorías. Con Plotly, puedes crear un gráfico de barras animado en R que muestre la evolución de tus datos.
#Basic Histogram
library(plotly)
fig <- plot_ly(x = ~rnorm(50), type = "histogram")

fig
#Normalized Histogram
library(plotly)
fig <- plot_ly(x = ~rnorm(50),
             type = "histogram",
             histnorm = "probability")

fig
#Specify Binning Function
library(plotly)

x = c("Apples","Apples","Apples","Organges", "Bananas")
y = c("5","10","3","10","5")

fig <- plot_ly(y=y, x=x, histfunc='sum', type = "histogram")
fig <- fig %>% layout(yaxis=list(type='linear'))

fig
#Horizontal histogram
library(plotly)
fig <- plot_ly(y = ~rnorm(50), type = "histogram")

fig
#Overlaid Histograms
fig <- plot_ly(alpha = 0.6)
fig <- fig %>% add_histogram(x = ~rnorm(500))
fig <- fig %>% add_histogram(x = ~rnorm(500) + 1)
fig <- fig %>% layout(barmode = "overlay")

fig
#Stacked Histograms
fig <- plot_ly(alpha = 0.6)
fig <- fig %>% add_histogram(x = ~rnorm(500))
fig <- fig %>% add_histogram(x = ~rnorm(500) + 1)
fig <- fig %>% layout(barmode = "stack")

fig
#Cumulative Histogram
library(plotly)
fig <- plot_ly(x = ~rnorm(50),
             type = "histogram",
             cumulative = list(enabled=TRUE))

fig
#Share bins between histograms
library(plotly)

fig <- plot_ly(
  type='histogram',
  x=~rnorm(100, 5),
  bingroup=1)

fig <- fig %>% add_trace(
  type='histogram',
  x=~rnorm(20, 5),
  bingroup=1)

fig <- fig %>% layout(
  barmode="overlay",
  bargap=0.1)

fig
#Note that traces on the same subplot, and with the same barmode ("stack", "relative", "group") are forced into the same bingroup, however traces with barmode = "overlay" and on different axes (of the same axis type) can have compatible bin settings. Histogram and histogram2d trace can share the same bingroup.

library(plotly)

fig <- plot_ly(
  type='histogram',
  x=~rnorm(100, 5))

fig <- fig %>% add_trace(
  type='histogram',
  x=~rnorm(20, 5))

fig <- fig %>% layout(
  barmode="stack",
  bargap=0.1)

fig
#Basic Bar Chart
library(plotly)

fig <- plot_ly(
  x = c("giraffes", "orangutans", "monkeys"),
  y = c(20, 14, 23),
  name = "SF Zoo",
  type = "bar"
)

fig
#Grouped Bar Chart
library(plotly)

Animals <- c("giraffes", "orangutans", "monkeys")
SF_Zoo <- c(20, 14, 23)
LA_Zoo <- c(12, 18, 29)
data <- data.frame(Animals, SF_Zoo, LA_Zoo)

fig <- plot_ly(data, x = ~Animals, y = ~SF_Zoo, type = 'bar', name = 'SF Zoo')
fig <- fig %>% add_trace(y = ~LA_Zoo, name = 'LA Zoo')
fig <- fig %>% layout(yaxis = list(title = 'Count'), barmode = 'group')

fig
#Stacked Bar Chart
library(plotly)

Animals <- c("giraffes", "orangutans", "monkeys")
SF_Zoo <- c(20, 14, 23)
LA_Zoo <- c(12, 18, 29)
data <- data.frame(Animals, SF_Zoo, LA_Zoo)

fig <- plot_ly(data, x = ~Animals, y = ~SF_Zoo, type = 'bar', name = 'SF Zoo')
fig <- fig %>% add_trace(y = ~LA_Zoo, name = 'LA Zoo')
fig <- fig %>% layout(yaxis = list(title = 'Count'), barmode = 'stack')

fig
#Bar Chart with Hover Text
library(plotly)

x <- c('Product A', 'Product B', 'Product C')
y <- c(20, 14, 23)
text <- c('27% market share', '24% market share', '19% market share')
data <- data.frame(x, y, text)

fig <- plot_ly(data, x = ~x, y = ~y, type = 'bar', text = text,
        marker = list(color = 'rgb(158,202,225)',
                      line = list(color = 'rgb(8,48,107)',
                                  width = 1.5)))
fig <- fig %>% layout(title = "January 2013 Sales Report",
         xaxis = list(title = ""),
         yaxis = list(title = ""))

fig
#Bar Chart with Direct Labels
library(plotly)

x <- c('Product A', 'Product B', 'Product C')
y <- c(20, 14, 23)
text <- c('27% market share', '24% market share', '19% market share')
data <- data.frame(x, y, text)

fig <- plot_ly(data, x = ~x, y = ~y, type = 'bar',
             text = y, textposition = 'auto',
             marker = list(color = 'rgb(158,202,225)',
                           line = list(color = 'rgb(8,48,107)', width = 1.5)))
fig <- fig %>% layout(title = "January 2013 Sales Report",
         xaxis = list(title = ""),
         yaxis = list(title = ""))

fig
#Grouped Bar Chart with Direct Labels
library(plotly)

x <- c('Product A', 'Product B', 'Product C')
y <- c(20, 14, 23)
y2 <- c(16,12,27)
text <- c('27% market share', '24% market share', '19% market share')
data <- data.frame(x, y, y2, text)

fig <- data %>% plot_ly()
fig <- fig %>% add_trace(x = ~x, y = ~y, type = 'bar',
             text = y, textposition = 'auto',
             marker = list(color = 'rgb(158,202,225)',
                           line = list(color = 'rgb(8,48,107)', width = 1.5)))
fig <- fig %>% add_trace(x = ~x, y = ~y2, type = 'bar',
            text = y2, textposition = 'auto',
            marker = list(color = 'rgb(58,200,225)',
                          line = list(color = 'rgb(8,48,107)', width = 1.5)))
fig <- fig %>% layout(title = "January 2013 Sales Report",
         barmode = 'group',
         xaxis = list(title = ""),
         yaxis = list(title = ""))

fig
#Rotated Bar Chart Labels
library(plotly)

x <- c('January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December')
y1 <- c(20, 14, 25, 16, 18, 22, 19, 15, 12, 16, 14, 17)
y2 <- c(19, 14, 22, 14, 16, 19, 15, 14, 10, 12, 12, 16)
data <- data.frame(x, y1, y2)

#The default order will be alphabetized unless specified as below:
data$x <- factor(data$x, levels = data[["x"]])

fig <- plot_ly(data, x = ~x, y = ~y1, type = 'bar', name = 'Primary Product', marker = list(color = 'rgb(49,130,189)'))
fig <- fig %>% add_trace(y = ~y2, name = 'Secondary Product', marker = list(color = 'rgb(204,204,204)'))
fig <- fig %>% layout(xaxis = list(title = "", tickangle = -45),
         yaxis = list(title = ""),
         margin = list(b = 100),
         barmode = 'group')

fig
#Customizing Bar Color
library(plotly)

x <- c('Feature A', 'Feature B', 'Feature C', 'Feature D', 'Feature E')
y <- c(20, 14, 23, 25, 22)
data <- data.frame(x, y)

fig <- plot_ly(data, x = ~x, y = ~y, type = 'bar', color = I("black"))
fig <- fig %>% layout(title = "Features",
         xaxis = list(title = ""),
         yaxis = list(title = ""))

fig
#Customizing Individual Bar Colors
library(plotly)

x <- c('Feature A', 'Feature B', 'Feature C', 'Feature D', 'Feature E')
y <- c(20, 14, 23, 25, 22)
data <- data.frame(x, y)

fig <- plot_ly(data, x = ~x, y = ~y, type = 'bar',
        marker = list(color = c('rgba(204,204,204,1)', 'rgba(222,45,38,0.8)',
                                'rgba(204,204,204,1)', 'rgba(204,204,204,1)',
                                'rgba(204,204,204,1)')))
fig <- fig %>% layout(title = "Least Used Features",
         xaxis = list(title = ""),
         yaxis = list(title = ""))

fig
#Customizing Individual Bar Widths
library(plotly)

x= c(1, 2, 3, 5.5, 10)
y= c(10, 8, 6, 4, 2)
width = c(0.8, 0.8, 0.8, 3.5, 4)
data <- data.frame(x, y, width)

fig <- plot_ly(data)
fig <- fig %>% add_bars(
    x= ~x,
    y= ~y,
    width = ~width
  )

fig
#Customizing Individual Bar Base
library(plotly)

fig <- plot_ly()
fig <- fig %>% add_bars(
    x = c("2016", "2017", "2018"),
    y = c(500,600,700),
    base = c(-500,-600,-700),
    marker = list(
      color = 'red'
    ),
    name = 'expenses'
  )
fig <- fig %>% add_bars(
    x = c("2016", "2017", "2018"),
    y = c(300,400,700),
    base = 0,
    marker = list(
      color = 'blue'
    ),
    name = 'revenue'
  )

fig
#Mapping a Color Variable
library(plotly)
library(dplyr)

fig <- ggplot2::diamonds
fig <- fig %>% count(cut, clarity)
fig <- fig %>% plot_ly(x = ~cut, y = ~n, color = ~clarity)

fig
## No trace type specified:
##   Based on info supplied, a 'bar' trace seems appropriate.
##   Read more about this trace type -> https://plotly.com/r/reference/#bar
#Colored and Styled Bar Chart
library(plotly)

x <- c(1995, 1996, 1997, 1998, 1999, 2000, 2001, 2002, 2003, 2004, 2005, 2006, 2007, 2008, 2009, 2010, 2011, 2012)
roW <- c(219, 146, 112, 127, 124, 180, 236, 207, 236, 263, 350, 430, 474, 526, 488, 537, 500, 439)
China <- c(16, 13, 10, 11, 28, 37, 43, 55, 56, 88, 105, 156, 270, 299, 340, 403, 549, 499)
data <- data.frame(x, roW, China)

fig <- plot_ly(data, x = ~x, y = ~roW, type = 'bar', name = 'Rest of the World',
        marker = list(color = 'rgb(55, 83, 109)'))
fig <- fig %>% add_trace(y = ~China, name = 'China', marker = list(color = 'rgb(26, 118, 255)'))
fig <- fig %>% layout(title = 'US Export of Plastic Scrap',
         xaxis = list(
           title = "",
           tickfont = list(
             size = 14,
             color = 'rgb(107, 107, 107)')),
         yaxis = list(
           title = 'USD (millions)',
           titlefont = list(
             size = 16,
             color = 'rgb(107, 107, 107)'),
           tickfont = list(
             size = 14,
             color = 'rgb(107, 107, 107)')),
         legend = list(x = 0, y = 1, bgcolor = 'rgba(255, 255, 255, 0)', bordercolor = 'rgba(255, 255, 255, 0)'),
         barmode = 'group', bargap = 0.15, bargroupgap = 0.1)

fig
## Warning: 'layout' objects don't have these attributes: 'bargroupgap'
## Valid attributes include:
## '_deprecated', 'activeshape', 'annotations', 'autosize', 'autotypenumbers', 'calendar', 'clickmode', 'coloraxis', 'colorscale', 'colorway', 'computed', 'datarevision', 'dragmode', 'editrevision', 'editType', 'font', 'geo', 'grid', 'height', 'hidesources', 'hoverdistance', 'hoverlabel', 'hovermode', 'images', 'legend', 'mapbox', 'margin', 'meta', 'metasrc', 'modebar', 'newshape', 'paper_bgcolor', 'plot_bgcolor', 'polar', 'scene', 'selectdirection', 'selectionrevision', 'separators', 'shapes', 'showlegend', 'sliders', 'smith', 'spikedistance', 'template', 'ternary', 'title', 'transition', 'uirevision', 'uniformtext', 'updatemenus', 'width', 'xaxis', 'yaxis', 'barmode', 'bargap', 'mapType'
#Waterfall Bar Chart
library(plotly)

x <- c('Product<br>Revenue', 'Services<br>Revenue', 'Total<br>Revenue', 'Fixed<br>Costs', 'Variable<br>Costs', 'Total<br>Costs', 'Total')
y <- c(400, 660, 660, 590, 400, 400, 340)
base <- c(0, 430, 0, 570, 370, 370, 0)
revenue <- c(430, 260, 690, 0, 0, 0, 0)
costs <- c(0, 0, 0, 120, 200, 320, 0)
profit <- c(0, 0, 0, 0, 0, 0, 370)
text <- c('$430K', '$260K', '$690K', '$-120K', '$-200K', '$-320K', '$370K')
data <- data.frame(x, base, revenue, costs, profit, text)

#The default order will be alphabetized unless specified as below:
data$x <- factor(data$x, levels = data[["x"]])

fig <- plot_ly(data, x = ~x, y = ~base, type = 'bar', marker = list(color = 'rgba(1,1,1, 0.0)'))
fig <- fig %>% add_trace(y = ~revenue, marker = list(color = 'rgba(55, 128, 191, 0.7)',
                                        line = list(color = 'rgba(55, 128, 191, 0.7)',
                                                    width = 2)))
fig <- fig %>% add_trace(y = ~costs, marker = list(color = 'rgba(219, 64, 82, 0.7)',
                                      line = list(color = 'rgba(219, 64, 82, 1.0)',
                                                  width = 2)))
fig <- fig %>% add_trace(y = ~profit, marker = list(color = 'rgba(50, 171, 96, 0.7)',
                                      line = list(color = 'rgba(50, 171, 96, 1.0)',
                                                  width = 2)))
fig <- fig %>% layout(title = 'Annual Profit - 2015',
         xaxis = list(title = ""),
         yaxis = list(title = ""),
         barmode = 'stack',
         paper_bgcolor = 'rgba(245, 246, 249, 1)',
         plot_bgcolor = 'rgba(245, 246, 249, 1)',
         showlegend = FALSE)
fig <- fig %>% add_annotations(text = text,
                  x = x,
                  y = y,
                  xref = "x",
                  yref = "y",
                  font = list(family = 'Arial',
                              size = 14,
                              color = 'rgba(245, 246, 249, 1)'),
                  showarrow = FALSE)

fig
#¿Para qué pueden servir los gráficos interactivos de plotly de histogramas o barras?
#Un gráfico de barras animado es una excelente opción para visualizar cambios a lo largo del tiempo o comparar diferentes categorías. Con Plotly, puedes crear un gráfico de barras animado en R que muestre la evolución de tus datos.

Including Plots

You can also embed plots, for example:

Note that the echo = FALSE parameter was added to the code chunk to prevent printing of the R code that generated the plot.