forked from sejja/Obesity-Risk
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathCA.R
More file actions
74 lines (41 loc) · 1.6 KB
/
Copy pathCA.R
File metadata and controls
74 lines (41 loc) · 1.6 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
library(dplyr)
library(knitr)
library(ca)
# Construct a contingency table
obesity_table <- table(obesity_data$CAEC, obesity_data$NObeyesdad) %>% as.data.frame.array() %>%
select(Insufficient_Weight,Normal_Weight,Overweight_Level_I,Overweight_Level_II,Obesity_Type_I,Obesity_Type_II,Obesity_Type_III)
kable(obesity_table)
# Calculate probability table
prob_table <- obesity_table/sum(obesity_table)
kable(prob_table)
# Perform Chi-Square test
xtest <- chisq.test(obesity_table)
xtest
# Calculate the total number of observations
total_observations <- sum(obesity_table)
# Get expected values
kable(round(xtest$expected, 0))
kable(round(xtest$expected,0) / total_observations)
# Is the difference big enough?
X2 <- sum(xtest$residuals^2)
# Let's compute the pvalue
xtest$p.value
# Relative contribution of each cell
(xtest$residuals^2)/xtest$statistic
# Perfrom eigendecomposition
M <- xtest$residuals/sqrt(total_observations)
M <- M%*%t(M)
eig <- eigen(M)
cumulative <- cumsum(eig$values)/sum(eig$values)
# Create a plot for explained variance
plot(1:length(eig$values), eig$values, ylim = c(0, 1.1), type = "b", pch = 19, col = "darkblue",
xlab = "Component", ylab = "Explained Variance",
main = "Explained Variance by Component")
lines(1:length(eig$values), cumulative, type = "b", pch = 19, col = "red")
legend("center", legend = c("Cumulative Variance","Explained Variance" ),col = c("red", "darkblue"), lty = 1, pch = 19)
# Let's perform ca
ca_table <- ca(obesity_table)
# Let's visualize it
plot(ca_table,invisible="row")
# The main indicators can be obtained with
summary(ca_table)