-
Notifications
You must be signed in to change notification settings - Fork 45
/
Copy pathPCA_application.R
52 lines (51 loc) · 1.85 KB
/
PCA_application.R
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
#------------------------------------------------------------------------------------------------------------------
#PCA analysis
#------------------------------------------------------------------------------------------------------------------
data_pca = data.frame(Recency,Frequency,Monetary)
colnames(data_pca) = c("Recency","Frequency","Monetary")
cov(data_pca)
cor(data_pca)
#pca with and without scaling
pca.data = prcomp(data_pca,scale = F)
pca.dataScale = prcomp(data_pca,scale = T) #with scaling
pca.dataScale$rotation
#the pca plots
biplot(pca.data, cex = 0.6)
biplot(pca.dataScale, cex = 0.6)
eig = eigen(cor(data_pca))
screeplot(pca.dataScale, type="l", npcs = 3, main = NULL)
pve = rep(NA, dim(data_pca)[2]) # proportion of variance explained
for(i in 1:3)
{
pve[i] = print(sum(eig$values[1:i])/3)
}
eig$values
pve
# generating new varaibles using the weights/loadings of pca
pca_Recency = pca.dataScale$rotation[1,1]*Recency_s
pca_Frequency = (-1)*pca.dataScale$rotation[2,1]*Frequency_s
pca_Monetary = (-1)*pca.dataScale$rotation[3,1]*Monetary_s
data_pca = data.frame(Recency,Frequency,Monetary)
colnames(data_pca) = c("Recency","Frequency","Monetary")
cov(data_pca)
cor(data_pca)
#pca with and without scaling
pca.data = prcomp(data_pca,scale = F)
pca.dataScale = prcomp(data_pca,scale = T) #with scaling
pca.dataScale$rotation
#the pca plots
biplot(pca.data, cex = 0.6)
biplot(pca.dataScale, cex = 0.6)
eig = eigen(cor(data_pca))
screeplot(pca.dataScale, type="l", npcs = 3, main = NULL)
pve = rep(NA, dim(data_pca)[2]) # proportion of variance explained
for(i in 1:3)
{
pve[i] = print(sum(eig$values[1:i])/3)
}
eig$values
pve
# generating new varaibles using the weights/loadings of pca
pca_Recency = pca.dataScale$rotation[1,1]*Recency_s
pca_Frequency = (-1)*pca.dataScale$rotation[2,1]*Frequency_s
pca_Monetary = (-1)*pca.dataScale$rotation[3,1]*Monetary_s