library(foreign)
library(ggplot2)
library(MASS)
library(openxlsx)
## Warning: package 'openxlsx' was built under R version 4.2.3
library(readr)
cereal <- read_csv("cereal.csv")
## Rows: 77 Columns: 16
## ── Column specification ────────────────────────────────────────────────────────
## Delimiter: ","
## chr  (3): name, mfr, type
## dbl (13): calories, protein, fat, sodium, fiber, carbo, sugars, potass, vita...
## 
## ℹ 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.
View(cereal)

LDA

#(y~x)
#prior = probabilidad de y, defaul 0.5,0.5
dis=lda(calories~protein+fat+sodium+fiber, data=cereal)
dis
## Call:
## lda(calories ~ protein + fat + sodium + fiber, data = cereal)
## 
## Prior probabilities of groups:
##         50         70         80         90        100        110        120 
## 0.03896104 0.02597403 0.01298701 0.09090909 0.22077922 0.37662338 0.12987013 
##        130        140        150        160 
## 0.02597403 0.03896104 0.02597403 0.01298701 
## 
## Group means:
##      protein       fat    sodium     fiber
## 50  2.333333 0.0000000  46.66667 5.0000000
## 70  4.000000 1.0000000 195.00000 9.5000000
## 80  2.000000 0.0000000   0.00000 3.0000000
## 90  2.571429 0.1428571  85.00000 3.4285714
## 100 3.000000 0.8235294 145.88235 1.8941176
## 110 2.103448 0.8620690 192.93103 0.8275862
## 120 2.300000 2.0000000 174.00000 2.7000000
## 130 3.000000 2.0000000 190.00000 1.7500000
## 140 3.000000 1.3333333 193.33333 3.0000000
## 150 4.000000 3.0000000 122.50000 3.0000000
## 160 3.000000 2.0000000 150.00000 3.0000000
## 
## Coefficients of linear discriminants:
##                  LD1          LD2          LD3          LD4
## protein  0.176372260 -0.195789731 -1.014263751 -0.419308950
## fat      0.678037054  0.949765400 -0.011557820  0.484446408
## sodium   0.008773355  0.002661286  0.004204921 -0.009224735
## fiber   -0.445383818  0.374842470  0.223075429 -0.069134772
## 
## Proportion of trace:
##    LD1    LD2    LD3    LD4 
## 0.5490 0.3001 0.0913 0.0596

#Nueva observación Nuevo cereal: protein = 3 fat = 2 sodium = 113 fiber = 12

nuevo.cereal=rbind(c(3,2,113,12))
colnames(nuevo.cereal)=colnames(cereal[,5:8])
nuevo.cereal=data.frame(nuevo.cereal)
predict(dis,newdata =nuevo.cereal)
## $class
## [1] 70
## Levels: 50 70 80 90 100 110 120 130 140 150 160
## 
## $posterior
##            50        70           80           90          100          110
## 1 0.001044507 0.9988735 1.433655e-06 3.148701e-05 2.526704e-07 5.017443e-08
##            120          130          140          150          160
## 1 4.308786e-05 1.849863e-08 2.553766e-06 1.387842e-07 2.958775e-06
## 
## $x
##         LD1      LD2      LD3       LD4
## 1 -4.046262 4.415687 1.528156 0.0372846