-
Notifications
You must be signed in to change notification settings - Fork 0
/
code.Rmd
569 lines (426 loc) · 21.3 KB
/
code.Rmd
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
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
---
title: "k-means"
author: "restu dn"
date: "4/5/2021"
output: word_document
---
```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = TRUE)
```
# Introduction
From Wikipedia:
# Feature engineering
```{r, warning=FALSE, message=FALSE}
# Load libraries
library(tidyverse)
library(scales)
library(ggthemes)
library(kableExtra)
library(plotly)
options(scipen = 999)
fifa_data <- read_csv("../input/data.csv") %>% select(-X1)
fifa_data <- fifa_data %>%
mutate(ValueMultiplier = ifelse(str_detect(Value, "K"), 1000, ifelse(str_detect(Value, "M"), 1000000, 1))) %>%
mutate(ValueNumeric_pounds = as.numeric(str_extract(Value, "[[:digit:]]+\\.*[[:digit:]]*")) * ValueMultiplier) %>%
mutate(Position = ifelse(is.na(Position), "Unknown", Position))
fifa_data <- fifa_data %>%
mutate(WageMultiplier = ifelse(str_detect(Wage, "K"), 1000, ifelse(str_detect(Wage, "M"), 1000000, 1))) %>%
mutate(WageNumeric_pounds = as.numeric(str_extract(Wage, "[[:digit:]]+\\.*[[:digit:]]*")) * WageMultiplier)
positions <- unique(fifa_data$Position)
gk <- "GK"
defs <- positions[str_detect(positions, "B$")]
mids <- positions[str_detect(positions, "M$")]
f1 <- positions[str_detect(positions, "F$")]
f2 <- positions[str_detect(positions, "S$")]
f3 <- positions[str_detect(positions, "T$")]
f4 <- positions[str_detect(positions, "W$")]
fwds <- c(f1, f2, f3, f4)
fifa_data <- fifa_data %>%
mutate(PositionGroup = ifelse(Position %in% gk, "GK", ifelse(Position %in% defs, "DEF", ifelse(Position %in% mids, "MID", ifelse(Position %in% fwds, "FWD", "Unknown")))))
fifa_data <- fifa_data %>%
mutate(AgeGroup = ifelse(Age <= 20, "20 and under", ifelse(Age > 20 & Age <=25, "21 to 25", ifelse(Age > 25 & Age <= 30, "25 to 30", ifelse(Age > 30 & Age <= 35, "31 to 35", "Over 35")))))
```
# Overall Ratings
```{r, message=FALSE, warning=FALSE, fig.width=12, fig.height=8}
fifa_data %>%
ggplot(aes(x= Overall)) +
geom_histogram(color = "white", fill = "darkgrey") +
ggtitle("Player Ratings Are Normally Distributed", subtitle = "The mean can be used as a measure of central tendancy") +
theme_fivethirtyeight() +
theme(axis.text.y = element_blank())
```
## Age vs Overall Rating
```{r, fig.width=12, fig.height=8}
fifa_data %>%
filter(!PositionGroup %in% c("GK", "Unknown")) %>%
group_by(Age) %>%
summarise(Rating = mean(Overall)) %>%
ggplot(aes(x= Age, y= Rating, group = 1)) +
geom_line(color = "grey50", size = 1) +
ggtitle("The Age Curve Flattens Off", subtitle = "Player ratings tend not to get better after the age of 30") +
xlab("Age") +
theme_fivethirtyeight() +
theme(axis.title = element_text(), axis.title.y = element_blank(), axis.title.x = element_text(face = "bold"))
```
```{r, fig.width=12, fig.height=8}
fifa_data %>%
filter(!PositionGroup %in% c("GK", "Unknown")) %>%
group_by(PositionGroup, Age) %>%
summarise(Rating = mean(Overall)) %>%
ggplot(aes(x= Age, y= Rating, group = PositionGroup)) +
geom_line(size = 1, color = "grey50") +
theme_fivethirtyeight() +
facet_wrap(~ PositionGroup, ncol = 1) +
theme(strip.background = element_rect(fill = "darkgrey"), strip.text = element_text(colour = "white", face = "bold"))
```
# Player Valuations
```{r, message=FALSE, warning=FALSE, fig.width=12, fig.height=8}
p <- fifa_data %>%
ggplot(aes(x= ValueNumeric_pounds)) +
geom_histogram(color = "white", fill = "darkgrey") +
scale_x_continuous(labels = dollar_format(prefix = "€")) +
ggtitle("Player Valuations Are Heavily Skewed", subtitle = "Long tail indicates there are some extreme outliers") +
theme_fivethirtyeight()
p +
geom_text(data = subset(fifa_data, Name == "Neymar Jr"), aes(x= ValueNumeric_pounds, y= 500, label=Name), color = "purple") +
geom_text(data = subset(fifa_data, Name == "L. Messi"), aes(x= ValueNumeric_pounds, y= 1000, label=Name), color = "purple") +
geom_text(data = subset(fifa_data, Name == "K. De Bruyne"), aes(x= ValueNumeric_pounds, y= 200, label=Name), color = "purple") +
geom_text(data = subset(fifa_data, Name == "E. Hazard"), aes(x= ValueNumeric_pounds, y= 500, label=Name), color = "purple") +
geom_text(data = subset(fifa_data, Name == "P. Dybala"), aes(x= ValueNumeric_pounds, y= 1000, label=Name), color = "purple")
```
## Age vs Valuations
```{r, message=FALSE, warning=FALSE, fig.width=12, fig.height=8}
fifa_data %>%
ggplot(aes(x= AgeGroup, y= ValueNumeric_pounds)) +
geom_boxplot(fill = "darkgrey") +
scale_y_log10(labels = dollar_format(prefix = "€")) +
ggtitle("Players Are In High Demand In Their Mid-20s", subtitle = "Valuation on a log scale, so differences \nbetween the age groups are significant") +
theme_fivethirtyeight()
```
## Position vs Valuations
```{r, message=FALSE, warning=FALSE, fig.width=12, fig.height=12}
a <- fifa_data %>%
filter(PositionGroup != "Unknown") %>%
ggplot(aes(x= PositionGroup, y= ValueNumeric_pounds)) +
geom_boxplot(fill = "darkgrey") +
scale_y_log10(labels = dollar_format(prefix = "€")) +
ggtitle("Positions to Break The Piggybank", subtitle = "Attackers and midfielders bring the fans to games... \nPay them the money!") +
theme_fivethirtyeight()
b <- fifa_data %>%
filter(PositionGroup != "Unknown") %>%
ggplot(aes(x= Position, y= ValueNumeric_pounds)) +
geom_boxplot(fill = "darkgrey") +
scale_y_log10(labels = dollar_format(prefix = "€")) +
coord_flip() +
theme_fivethirtyeight() +
facet_wrap(~ PositionGroup, scales = "free") +
theme(strip.background = element_rect(fill = "darkgrey"), strip.text = element_text(colour = "white", face = "bold"))
gridExtra::grid.arrange(a, b)
```
## Player Rating and Valuations
```{r, message=FALSE, warning=FALSE, fig.width=12, fig.height=8}
fifa_data %>%
filter(PositionGroup != "Unknown") %>%
ggplot(aes(x= Overall, y= ValueNumeric_pounds)) +
geom_point(position = "jitter", color = "darkgrey") +
ggtitle("Higher Ratings Cost More Money", subtitle = "There are still some high rating players that \ndon't cost an arm and a leg") +
scale_y_continuous(labels = dollar_format(prefix = "€")) +
theme_fivethirtyeight() +
annotate("text", x= 70, y= 97000000, label = paste0("Spearman Correlation: ", round(cor(fifa_data$Overall, fifa_data$ValueNumeric_pounds, method = "spearman"),4)), color = "darkgreen", size = 8)
```
## Correlations with a players Overall rating
```{r, message=FALSE, warning=FALSE, fig.width=12, fig.height=12}
gk_vars <- fifa_data %>% select(contains("GK")) %>% names()
spearman_cor_with_overall <- fifa_data %>%
filter(Position != "GK") %>%
select_if(is.numeric) %>%
select(-gk_vars, -ID, - `Jersey Number`, -ValueMultiplier, -WageMultiplier) %>%
as.matrix() %>%
na.omit() %>%
cor(method = "spearman")
pearson_cor_with_overall <- fifa_data %>%
filter(Position != "GK") %>%
select_if(is.numeric) %>%
select(-gk_vars, -ID, - `Jersey Number`, -ValueMultiplier, -WageMultiplier) %>%
as.matrix() %>%
na.omit() %>%
cor()
cor_colnames <- colnames(spearman_cor_with_overall)
spearman_cor_with_overall <- spearman_cor_with_overall[,2] %>% data.frame()
spearman_cor_with_overall <- cbind(cor_colnames, spearman_cor_with_overall) %>% arrange(desc(`.`))
pearson_cor_with_overall <- pearson_cor_with_overall[,2] %>% data.frame()
pearson_cor_with_overall <- cbind(cor_colnames, pearson_cor_with_overall) %>% arrange(desc(`.`))
spearman_cor_with_overall %>% left_join(pearson_cor_with_overall, by = "cor_colnames") %>%
rename(Feature = cor_colnames, Spearman = `..x`, Pearson = `..y`) %>% filter(Feature != "Overall") %>% head(10)
# spearman_cor_with_overall %>% left_join(pearson_cor_with_overall, by = "cor_colnames") %>%
# rename(Feature = cor_colnames, Spearman = `..x`, Pearson = `..y`) %>% filter(Feature != "Overall") %>% tail(10)
```
## Which positions are skilled in which attributes
```{r, message=FALSE, warning=FALSE, fig.width=12, fig.height=12}
tile_data <- fifa_data %>%
select_if(is.numeric) %>%
select(-gk_vars) %>%
left_join(fifa_data %>% select(ID, Position, PositionGroup), by = "ID") %>%
filter(Overall >= 70) %>%
select(-ID, -`International Reputation`, -`Jersey Number`, -`Skill Moves`, -Special, -ValueMultiplier, -ValueNumeric_pounds, -`Weak Foot`, -Age, -Overall, -Potential, -starts_with("Wage"))
tile_data <- tile_data %>%
filter(Position != "GK") %>%
gather(key = Attribute, value = Value, -Position, -PositionGroup) %>%
group_by(PositionGroup, Position, Attribute) %>%
summarise(MedianValue = median(Value, na.rm = T))
tile_data %>%
filter(Position != "Unknown") %>%
ggplot(aes(x= Attribute, y= Position)) +
geom_tile(aes(fill = MedianValue), colour = "black") +
geom_text(aes(label = MedianValue)) +
scale_fill_gradient(low = "purple", high = "green") +
ggtitle("Centre Backs Are Strong, Left Forwards Are Agile", subtitle = "Analysing the median ratings for each of the attributes for \neach position for players with and overall rating over 75") +
theme_fivethirtyeight() +
theme(axis.text.x = element_text(angle = 45, hjust = 1), strip.text = element_text(face = "bold", size = 12), legend.position = "none") +
facet_wrap(~ PositionGroup, scales = "free", ncol = 1)
```
***
# Helping me manage a team
## Young Player Analysis
```{r, message=FALSE, warning=FALSE, fig.width=12, fig.height=8}
holder <- fifa_data %>%
mutate(RoomToGrow = Potential - Overall) %>%
arrange(desc(RoomToGrow)) %>%
head(n=20) %>%
select(Name, Value, Overall, Age, RoomToGrow, Position) %>%
gather(key = Mult, value = ExpectedValue, -Name, -Value, -Age, -Position) %>%
mutate(Mult = factor(x=Mult, levels = c("RoomToGrow", "Overall")))
holder %>%
ggplot(aes(x= Name, y= ExpectedValue, fill = Mult)) +
geom_bar(stat = "identity", position = "stack", color = "black") +
coord_flip() +
scale_fill_manual(values = c("Overall" = "green", "RoomToGrow" = "violet")) +
ggtitle("Players To Grow With Your Team", subtitle = "Plotted are the 20 players with the highest remaining room to grow") +
theme_fivethirtyeight() +
theme(legend.position = "none") +
geom_text(data = subset(holder, Mult == "Overall"), aes(x= Name, y= 10, label=paste(Position, Value, Age, sep = ", "))) +
annotate("text", x= 14.5, y= 80, label = "The 'potential' left \nin the player")
####### Need to put in a left pointing arrow
```
## When does potential end?
```{r, message=FALSE, warning=FALSE, fig.width=12, fig.height=8}
fifa_data %>%
group_by(Age) %>%
summarise(Potential = mean(Potential),
Overall = mean(Overall)) %>%
ggplot(aes(x= Age)) +
geom_line(aes(y= Potential), color = "purple", size = 1) +
geom_line(aes(y= Overall), color = "grey50", size = 1) +
annotate("text", x= 30, y=71, label = "Potential meets overall\ntalent at 29 years old", color = "purple") +
ggtitle("Potential And Overall Talent Converges", subtitle = "The average ratings were taken for each age") +
theme_fivethirtyeight()
```
# Free Valuation Players
```{r, message=FALSE, warning=FALSE, fig.width=12, fig.height=8}
fifa_data %>%
filter(ValueNumeric_pounds == 0, PositionGroup != "Unknown") %>%
mutate(PotentialOver80 = ifelse(Potential >= 80, "Yes", "No")) %>%
ggplot(aes(x= Age, y= Overall)) +
geom_vline(xintercept = 30, color = "black", linetype = 2) +
geom_hline(yintercept = 65, color = "black", linetype = 2) +
geom_text(aes(label = Name, colour = PotentialOver80), check_overlap = T) +
scale_colour_manual(values = c("lightgrey", "purple")) +
theme_fivethirtyeight() +
theme(axis.text = element_text(face = "bold"), legend.position = "none") +
ggtitle("There's No Such Thing As A Free Lunch... Or Is There?", subtitle = "Plotting player age versus their overall rating for all players with a \nvaluation of €0. Purple names have potential over 80.") +
annotate("text", x= 20, y= 79, label = "Rebuilding \ntarget area", size = 8, color = "darkgreen") +
annotate("text", x= 43, y= 79, label = "Win-Now \ntarget area", size = 8, color = "darkgreen")
```
***
# Which Team do I want to manage
## Team Age
```{r, message=FALSE, warning=FALSE, fig.width=12, fig.height=8}
age_avg <- mean(fifa_data$Age)
age_sd <- sd(fifa_data$Age)
team_age <- fifa_data %>%
group_by(Club) %>%
summarise(AvgAge = mean(Age)) %>%
mutate(AgeZ_score = (AvgAge - age_avg) / age_sd)
team_age <- team_age %>%
mutate(AgeType = ifelse(AgeZ_score <0, "Below", "Above"))
team_age <- team_age %>%
arrange(desc(AgeZ_score)) %>%
head(20) %>%
rbind(team_age %>% arrange(desc(AgeZ_score)) %>% tail(20))
team_age %>%
ggplot(aes(x= reorder(Club,AgeZ_score), y= AgeZ_score)) +
geom_bar(stat = 'identity', aes(fill = AgeType), colour = "white") +
geom_text(aes(label = round(AvgAge,1))) +
scale_fill_manual(values = c("purple", "green")) +
coord_flip() +
ggtitle("Nordic Clubs Are Younger Than South American Clubs", subtitle = "Ranking the 20 oldest playing lists vs the 20 youngest playing lists") +
theme_fivethirtyeight() +
theme(legend.position = "none", axis.text.x = element_blank())
```
## Team Overall Talent
```{r,message=FALSE, warning=FALSE, fig.width=12, fig.height=8}
top_20_overall_clubs <- fifa_data %>%
group_by(Club) %>%
summarise(AverageRating = mean(Overall, na.rm = T)) %>%
arrange(desc(AverageRating)) %>%
head(n = 20) %>% pull(Club)
fifa_data %>%
filter(Club %in% top_20_overall_clubs) %>%
mutate(Top3 = ifelse(Club %in% c("Juventus", "Napoli", "Inter"), "Yes", "No")) %>%
ggplot(aes(x= reorder(Club,Overall), y= Overall, fill = Top3)) +
geom_boxplot(color = "black") +
scale_fill_manual(values = c("lightgrey", "purple")) +
ggtitle("Italian Teams Have The Highest Overall Ratings", subtitle = "The average overall rating of the 20 highest rated teams in the game, sorted in descending order") +
coord_flip() +
theme_fivethirtyeight() +
theme(legend.position = "none")
```
```{r, message=FALSE, warning=FALSE, fig.width=12, fig.height=8}
fifa_data %>%
mutate(ElitePlayers = ifelse(Overall >= 85, "Elite", "Not Elite")) %>%
group_by(Club, ElitePlayers) %>%
filter(ElitePlayers == "Elite") %>%
summarise(NumberElitePlayers = n()) %>%
filter(NumberElitePlayers >1) %>%
mutate(Top3 = ifelse(Club %in% c("Juventus", "Napoli", "Inter"), "Yes", "No")) %>%
arrange(desc(NumberElitePlayers)) %>%
ggplot(aes(x= reorder(Club,NumberElitePlayers), y= NumberElitePlayers, fill = Top3)) +
geom_col(color = "black") +
scale_fill_manual(values = c("lightgrey", "purple")) +
ggtitle("However If You Define Talent As Number Of Superstars", subtitle = "Plotted are clubs with more than one 'elite' player. Elite players being those with a rating greater than 85") +
scale_y_continuous(breaks = seq(0,12,1))+
coord_flip() +
theme_fivethirtyeight() +
theme(legend.position = "none")
```
## Deadly Teams Up Front
```{r}
fifa_data <- fifa_data %>%
mutate(AttackingRating = (Finishing + LongShots + Penalties + ShotPower + Positioning) /5)
fifa_data %>%
filter(PositionGroup %in% c("MID", "FWD")) %>%
group_by(Club) %>%
summarise(NumberOfAttackers = n(), TeamAttackingRating = mean(AttackingRating)) %>%
arrange(desc(TeamAttackingRating)) %>% head(50) %>%
DT::datatable()
```
## Team Wage Bills and Value for Money
```{r, fig.width=12, fig.height=8}
fifa_data %>%
group_by(Club) %>%
summarise(TotalWages = sum(WageNumeric_pounds, na.rm = T),
AverageRating = mean(Overall, na.rm = T)) %>%
mutate(ValueForMoney = TotalWages / AverageRating) %>%
arrange(desc(TotalWages)) %>% head(n= 20) %>%
mutate(Top2 = ifelse(Club %in% c("Real Madrid", "FC Barcelona"), "Top", ifelse(Club %in% c("Inter", "Milan", "Napoli"), "Val", "No"))) %>%
ggplot(aes(x= reorder(Club, TotalWages), y= TotalWages, fill = Top2)) +
geom_col(colour = "black") +
geom_text(aes(label = dollar(round(ValueForMoney), prefix = "€"), hjust = 0)) +
scale_fill_manual(values = c("lightgrey", "purple", "green")) +
scale_y_continuous(labels = dollar_format(prefix = "€")) +
coord_flip() +
ggtitle("The Spaniards Really Know How To Spend, \nBut Italians Are Shrewd", subtitle = "The 20 highest weekly wage bills in FIFA19 and how much one rating point costs in wages") +
theme_fivethirtyeight() +
theme(legend.position = "none")
```
```{r, fig.width=12, fig.height=8}
fifa_data %>%
group_by(Club) %>%
filter(!is.na(Club)) %>%
summarise(TotalWages = sum(WageNumeric_pounds, na.rm = T),
AverageRating = mean(Overall, na.rm = T)) %>%
mutate(ValueForMoney = TotalWages / AverageRating) %>%
arrange(desc(ValueForMoney)) %>% tail(n= 20) %>%
mutate(Over70 = ifelse(AverageRating >= 70, "Yes", "No")) %>%
ggplot(aes(x= reorder(Club, -TotalWages), y= TotalWages, fill = Over70)) +
geom_col(colour = "black") +
geom_text(aes(label = dollar(round(ValueForMoney), prefix = "€"), hjust = 1)) +
scale_fill_manual(values = c("lightgrey", "green")) +
scale_y_continuous(labels = dollar_format(prefix = "€")) +
coord_flip() +
ggtitle("Extracting Value For Money", subtitle = "The 20 clubs who spend the least amount of wage pounds per overall rating point.\nHighlighted clubs have an average rating over 70") +
theme_fivethirtyeight() +
theme(legend.position = "none")
```
***
# K-Means Clustering
```{r, message=FALSE, warning=FALSE, fig.width=12, fig.height=8}
# Get data ready
data_cluster <- fifa_data %>%
filter(PositionGroup != "Unknown") %>%
filter(PositionGroup != "GK") %>%
mutate(RoomToGrow = Potential - Overall) %>%
select_if(is.numeric) %>%
select(-ID, -`Jersey Number`, -AttackingRating, -starts_with("Value"), - starts_with("Wage"), -starts_with("GK"), -Overall)
scaled_data <- scale(data_cluster)
set.seed(109)
# Initialize total within sum of squares error: wss
wss <- 0
# For 1 to 30 cluster centers
for (j in 1:30) {
km.out <- kmeans(scaled_data, centers = j, nstart = 20)
# Save total within sum of squares to wss variable
wss[j] <- km.out$tot.withinss
}
# create a DF to use in a ggplot visualisation
wss_df <- data.frame(num_cluster = 1:30, wgss = wss)
# plot to determine optimal k
ggplot(data = wss_df, aes(x=num_cluster, y= wgss)) +
geom_line(color = "lightgrey", size = 2) +
geom_point(color = "green", size = 4) +
theme_fivethirtyeight() +
geom_curve(x=14, xend=8, y=300000, yend= 290500, arrow = arrow(length = unit(0.2,"cm")), size =1, colour = "purple") +
geom_text(label = "k = 8\noptimal level", x=14, y= 290000, colour = "purple") +
labs(title = "Using Eight Clusters To Group Players", subtitle = "Selecting the point where the elbow 'bends', or where the slope of \nthe Within groups sum of squares levels out")
# Set k equal to the number of clusters corresponding to the elbow location
k <- 8
# Create a k-means model on wisc.data: wisc.km
wisc.km <- kmeans(scale(data_cluster), centers = k, nstart = 20)
# add the cluster group back to the original DF for all players other than GK and Unknown
cluster_data <- fifa_data %>%
filter(PositionGroup != "Unknown") %>%
filter(PositionGroup != "GK") %>%
mutate(Cluster = wisc.km$cluster)
```
```{r, message=FALSE, warning=FALSE, fig.width=12, fig.height=8}
# create a new DF with just some select variables for analysis
cluster_analysis <- cluster_data %>%
select(ID, Name, Club, Age, PositionGroup, Overall, Cluster, ValueNumeric_pounds)
# how have the clusters been split between position groups
table(cluster_analysis$Cluster, cluster_analysis$PositionGroup)
# create an arranged DF for analysis
cluster_arranged <- cluster_analysis %>%
mutate(Cluster = as.character(Cluster)) %>%
arrange(desc(Overall)) %>%
group_by(Cluster)
```
```{r, message=FALSE, warning=FALSE, fig.width=15, fig.height=8}
# build the plot for each of the 20 highest rated players in each cluster
p <- cluster_analysis %>%
mutate(Cluster = paste("Cluster: ", Cluster, sep = "")) %>%
arrange(desc(Overall)) %>%
group_by(Cluster) %>%
slice(1:20) %>%
mutate(Under27 = ifelse(Age < 27, "Yes", "No")) %>%
ggplot(aes(x= Overall, y= ValueNumeric_pounds)) +
geom_point(position = "jitter", shape = 21, color = "black", size = 2, aes(text = paste(Name, PositionGroup), fill = Under27)) +
scale_fill_manual(values = c("purple", "green")) +
scale_y_continuous(labels = dollar_format(prefix = "€")) +
ggtitle("Player's overall rating plotted against their value for the \n20 highest rated players in each cluster") +
facet_wrap(~ factor(Cluster), scales = "free", ncol = 2) +
theme_fivethirtyeight() +
theme(legend.position = "none", strip.text = element_text(face = "bold", size = 12))
# plot output
ggplotly(p, height = 700, width = 900)
```
```{r}
return_similar_players <- function(player, num_results, return_within_fraction) {
cluster_filter <- cluster_analysis$Cluster[cluster_analysis$Name == player]
player_value <- cluster_analysis$ValueNumeric_pounds[cluster_analysis$Name == player]
cluster_analysis %>%
filter(Cluster == cluster_filter,
ValueNumeric_pounds >= (player_value * (1- return_within_fraction)) & ValueNumeric_pounds <= (player_value * (1 + return_within_fraction))) %>%
head(num_results)
}
return_similar_players("I. Perišić", 100, .05) %>% DT::datatable()
```