library(readxl)
library(tidyverse)
library(dplyr)
library(sysfonts)
library(ggplot2)
library(ggimage)
library(ggtext)
library(maps)
library(geosphere)
library(BBmisc)
library(randomNames)
library(networkD3)

font_paths("/Users/theotimebourgeois/Library/Fonts/AvertaPE-Black.otf")
font_add(family = "AvertaPE-Black.otf",
         regular = "AvertaPE-Black.otf")
font_paths("/Users/theotimebourgeois/Library/Fonts/AvertaPE-Regular.otf")
font_add(family = "AvertaPE-Regular.otf",
         regular = "AvertaPE-Regular.otf")

font <- "AvertaPE-Regular"

purple <- c("#2C2C54")
pink <- c("#A40E4C")
blue <- c("#2E86AB")
yellow <- c("#FF9C00")
lila <- c("#E3DFFF")
brown <- c("#C3979F")
grey <- c("#F2F2F2")
white <- c("#FFFFFF")

colfunc <- colorRampPalette(c(pink, blue, purple, yellow))
colfunc2 <- colorRampPalette(c(pink,yellow,lila,purple))
colfunc3 <- colorRampPalette(c(pink,yellow,purple))

FormDB <- read_excel("/Users/theotimebourgeois/Downloads/Mobile payment methods, use according to your network? (réponses).xlsx", sheet = "Réponses au formulaire 1")

SourceText <- "Source: ‟Mobile payment methods, use according to your network?”\nForm performed by Théotime Bourgeois"
People <- nrow(FormDB)

FormDB[,6:29][ FormDB[,6:29] == "5 (Strongly agree)" ] <- "5"
FormDB[,6:29][ FormDB[,6:29] == "1 (Strongly disagree)" ] <- "1"
FormDB[,6:29] <- FormDB[,6:29] %>% mutate_if(is.character,as.numeric)

FormDB$LastName <-
  FormDB$`Your last name (Your family name will be anonymized: it is only useful to identify your family group):` %>% toupper

FormDB <- FormDB %>% select(-`Your last name (Your family name will be anonymized: it is only useful to identify your family group):`)

FormDB$`Name of your company:` <- FormDB$`Name of your company:` %>% toupper

FormDB$`Approximate start date of your studies:` <- FormDB$`Approximate start date of your studies:` %>% format("%Y")
FormDB$`Approximate end date of your studies:` <- FormDB$`Approximate end date of your studies:` %>% format("%Y")

FormDB <- FormDB %>% 
  mutate(ID=1,
         ID=cumsum(ID),
         ID=paste("Person",ID))

Gender <- FormDB$`Your gender:` %>% table() %>% prop.table() %>% as.data.frame()

FormDB$Link[FormDB$ID=="Person 2"] <- "Person 1"
FormDB$Link[FormDB$ID=="Person 21"] <- "Person 9"
FormDB$Link[FormDB$ID=="Person 24"] <- "Person 7"
FormDB$Link[FormDB$ID=="Person 26"] <- "Person 7"
FormDB$Link[FormDB$ID=="Person 28"] <- "Person 7"
FormDB$Link[FormDB$ID=="Person 29"] <- "Person 7"
FormDB$Link[FormDB$ID=="Person 27"] <- "Person 1"
FormDB$Link[FormDB$ID=="Person 27"] <- "Person 1"
FormDB$Link[FormDB$ID=="Person 30"] <- "Person 7"
FormDB$Link[FormDB$ID=="Person 31"] <- "Person 8"
FormDB$Link[FormDB$ID=="Person 32"] <- "Person 7"
FormDB$Link[FormDB$ID=="Person 33"] <- "Person 1"
FormDB$Link[FormDB$ID=="Person 37"] <- "Person 38"
FormDB$Link[FormDB$ID=="Person 39"] <- "Person 7"
FormDB$Link[FormDB$ID=="Person 34"] <- "Person 7"
FormDB$Link[FormDB$ID=="Person 35"] <- "Person 7"
FormDB$Link[FormDB$ID=="Person 36"] <- "Person 7"
FormDB$Link[FormDB$ID=="Person 41"] <- "Person 2"
FormDB$Link[FormDB$ID=="Person 45"] <- "Person 43"
FormDB$Link[FormDB$ID=="Person 50"] <- "Person 7"

FormDB$Name <- randomNames(nrow(FormDB), which.names="first")

UTAUT_List <- FormDB[6:29] %>% colnames() %>% as.data.frame()

UTAUT_List <- strsplit(UTAUT_List$.,"\\[") %>% as.data.frame() %>% t()
rownames(UTAUT_List) <- 1:nrow(UTAUT_List)
PurposeOT <- FormDB$`I make online transactions to : (check all that apply to you)` %>%
  strsplit(", ") %>%
  unlist() %>%
  table() %>%
  as.data.frame() %>% 
  `colnames<-`(c("Purpose","Freq")) %>%
  arrange(desc(Freq)) %>%
  mutate(
    Purpose = sapply(Purpose %>% str_split("\\("), `[`, 1),
    Purpose = factor(Purpose, levels=rev(Purpose)))

PurposeOT <- PurposeOT %>% mutate(
    ID = 1:nrow(PurposeOT),
    label = paste0(Purpose,": ",Freq))

PurposeGraph <- ggplot(PurposeOT, aes(x = ID, y = Freq, fill = Purpose)) +
  geom_segment(aes(x = 1:nrow(PurposeOT), xend = 1:nrow(PurposeOT), y = People, yend = 0),col = grey)+
  geom_bar(width = 0.9, stat="identity")+
  geom_segment(aes(x = 0, xend = nrow(PurposeOT)+1, y = 0, yend = 0))+
  coord_polar(theta = "y")+
  scale_fill_manual(values=colfunc(nrow(PurposeOT)))+
  xlim(c(-5,1+nrow(PurposeOT))) +
  ylim(c(0,People)) +
  geom_text(hjust = 1.05, size = 3, family = font,
          aes(x = ID, y = 0, label = label)) +
  geom_richtext(size = 4.5, col = purple,family = "AvertaPE-Black", fill = NA, label.color = NA,
   aes(x = -5, y = 0,
       label=paste0("On a sample of <br><span style='font-size:25pt; color:",
                    pink,"'> **",People," people**</span>")))+
  labs(title="Main reasons for using these applications",
    y=NULL,x=NULL, fill="Skills",
    caption=SourceText)+
  theme_minimal() +
  theme(legend.position = "none",
        panel.grid.major = element_blank(),
        panel.grid.minor = element_blank(),
        plot.title = element_text(size = 15, family = "AvertaPE-Black", color = purple),
        plot.caption = element_text(size = 8, color = blue),
        axis.line = element_blank(),
        axis.text.y = element_blank(),
        axis.text.x = element_blank(),
        axis.ticks = element_blank())

ggsave("Purpose.png", PurposeGraph)
## Saving 7 x 5 in image
PurposeGraph

HowOT <- FormDB$`What is the reason for this?` %>%
  strsplit(", ") %>%
  unlist() %>%
  table() %>%
  as.data.frame() %>% 
  `colnames<-`(c("How","Freq")) %>%
  arrange(desc(Freq)) %>%
  mutate(
    How = sapply(How %>% str_split("\\("), `[`, 1),
    How = factor(How, levels=rev(How)))

HowOT$How <- HowOT$How %>% droplevels() %>% as.character()

HowOT$How[HowOT$How %>% str_detect("institution")] <- "Existing user institution"
HowOT$How[HowOT$How %>% str_detect("knew")] <- "Option already known"
HowOT$How[HowOT$How %>% str_detect("payment")] <- "Time of payment"
HowOT$How[HowOT$How %>% str_detect("friend")] <- "Conversion by a friend"
HowOT$How[HowOT$How %>% str_detect("need")] <- "Meet a need"

HowOT$How[HowOT$Freq <= 2] <- "Other"

HowOT <- HowOT %>%
  group_by(How) %>%
  summarise(Freq = sum(Freq))

HowOT <- HowOT %>% 
  arrange(desc(Freq)) %>% 
  mutate(ID = 1:nrow(HowOT),
    label = paste0(How,": ",Freq),
    How = factor(How, levels=rev(How)))

HowGraph <- ggplot(HowOT, aes(x = ID, y = Freq, fill = How)) +
  geom_segment(aes(x = 1:nrow(HowOT), xend = 1:nrow(HowOT), y = max(Freq)+1, yend = 0),col = grey)+
  geom_bar(width = 0.9, stat="identity")+
  geom_segment(aes(x = 0, xend = nrow(HowOT)+1, y = 0, yend = 0))+
  coord_polar(theta = "y")+
  scale_fill_manual(values=colfunc(nrow(HowOT)))+
  xlim(c(-5,1+nrow(HowOT))) +
  ylim(c(0,max(HowOT$Freq)+1)) +
  geom_text(hjust = 1.05, size = 3, family = font,
          aes(x = ID, y = 0, label = label)) +
  geom_richtext(size = 4.5, col = purple,family = "AvertaPE-Black", fill = NA, label.color = NA,
   aes(x = -5, y = 0,
       label =paste0("On a sample of <br><span style='font-size:25pt; color:",
                    pink,"'> **",People," people**</span>")))+
  labs(title="Conversion mostly done thanks to users",
       subtitle = "Institutions as majority converters",
    y=NULL,x=NULL, fill="Skills",
    caption=SourceText)+
  theme_minimal() +
  theme(legend.position = "none",
        panel.grid.major = element_blank(),
        panel.grid.minor = element_blank(),
        plot.title = element_text(size = 15, family = "AvertaPE-Black", color = purple),
        plot.caption = element_text(size = 8, color = blue),
        axis.line = element_blank(),
        axis.text.y = element_blank(),
        axis.text.x = element_blank(),
        axis.ticks = element_blank())

ggsave("How.png", HowGraph)

HowGraph

Market <- FormDB$`What mobile applications/payment methods do you use to transfer money to a friend?` %>%
  strsplit(", ") %>%
  unlist() %>%
  table() %>%
  as.data.frame() %>% 
  `colnames<-`(c("Market","Freq")) %>% 
  droplevels.data.frame()

Market$Image[Market$Market %>% str_detect("Lydia")] <- "Lydia.png"
Market$Image[Market$Market %>% str_detect("RIB")] <- "RIB.png"
Market$Image[Market$Market %>% str_detect("Check")] <- "Check.png"
Market$Image[Market$Market %>% str_detect("Lyf Pay")] <- "Lyf pay.png"
Market$Image[Market$Market %>% str_detect("Pumpkin")] <- "Pumpkin.png"
Market$Image[Market$Market %>% str_detect("Paylib")] <- "PayLib.png"
Market$Image[Market$Market %>% str_detect("PayPal")] <- "PayPal.png"

Market <- Market %>%
  arrange(desc(Freq)) %>%
  head(7) %>% 
  mutate(Market = factor(Market, levels=rev(Market)))

size <- 10

Market_graph <- ggplot(Market, aes(y = factor(Market)))+
  geom_segment(aes(x = 0, xend = Freq-1.9, yend = Market), size = size, col = purple)+
  geom_point(aes(x = Freq-1.9), size = size*0.95, col = yellow)+
  geom_image(aes(x = Freq, image=Image,),
             asp = 1.8,
             size=.07)+
  geom_text(aes(x=Freq-1.9, label = Freq), col = white, family = "AvertaPE-Black")+
  labs(title="New payment methods: a complement to traditional methods",
       subtitle="Use of payment methods in respondents' daily lives",
       y=NULL, x="Count",
       caption = SourceText)+
  scale_y_discrete(labels = function(y) str_wrap(y, width = 12))+
  theme(text=element_text(size=12, family="AvertaPE-Regular"),
        panel.background = element_blank(),
        legend.position = "right",
        legend.background = element_blank(),
        axis.line = element_line(colour = purple),
        plot.title = element_text(size = 15, family = "AvertaPE-Black", color = purple),
        plot.caption = element_text(size = 10, color = blue))

ggsave("Market.png", Market_graph)

Market_graph

FormDB$Age <- (Sys.Date() %>% format("%Y") %>% as.numeric())-FormDB$`Your year of birth:`

AppAge <- FormDB %>%
  select(`What mobile applications/payment methods do you use to transfer money to a friend?`,Age) %>%
  `colnames<-`(c("App","Age")) %>% 
  separate(col=App,sep=", ",c("1","2","3","4","5"))
## Warning: Expected 5 pieces. Missing pieces filled with `NA` in 50 rows [1, 2, 3,
## 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, ...].
AppAge <- rbind(
  AppAge %>% select(1,6) %>% `colnames<-`(c("App","Age")),
  AppAge %>% select(2,6) %>% `colnames<-`(c("App","Age")),
  AppAge %>% select(3,6) %>% `colnames<-`(c("App","Age")),
  AppAge %>% select(4,6) %>% `colnames<-`(c("App","Age")),
  AppAge %>% select(5,6) %>% `colnames<-`(c("App","Age"))) %>% 
  group_by(App) %>% 
  summarise(Age=mean(Age) %>% round(0)) %>% 
  `colnames<-`(c("Market","Age"))

AppAge <- merge(Market,AppAge, by="Market") %>%
  arrange(desc(Age)) %>% 
  mutate(Market = factor(Market, levels=rev(Market)))

AppAge_graph <- ggplot(AppAge, aes(y = factor(Market)))+
  geom_segment(aes(x = 0, xend = Age-3, yend = Market), size = size, col = purple)+
  geom_point(aes(x = Age-3), size = size*0.95, col = yellow)+
  geom_image(aes(x = Age, image=Image,),
             asp = 1,
             size=.07)+
  geom_text(aes(x=Age-3, label = Age), col = white, family = "AvertaPE-Black")+
  labs(title="The older the technology, the higher the average age of users",
       subtitle="New technologies appeal to young people",
       y=NULL, x="Age",
       caption = SourceText)+
  scale_y_discrete(labels = function(y) str_wrap(y, width = 12))+
  theme(text=element_text(size=12, family="AvertaPE-Regular"),
        panel.background = element_blank(),
        legend.position = "right",
        legend.background = element_blank(),
        axis.line = element_line(colour = purple),
        plot.title = element_text(size = 15, family = "AvertaPE-Black", color = purple),
        plot.caption = element_text(size = 10, color = blue))

ggsave("AppAge.png", AppAge_graph)
## Saving 7 x 5 in image
AppAge_graph

ZIPCodeDB <- read_csv("/Users/theotimebourgeois/Documents/Cours/BSB/MASTER2/Thesis/R New Thesis/cities.csv")
#https://www.data.gouv.fr/en/datasets/regions-departements-villes-et-villages-de-france-et-doutre-mer/

ZIPDB <- FormDB %>%
  select(`Postal code of your company:`,`Postal code of your recently attended school:`,`Your postal code:`) %>% 
  as.data.frame() %>% 
  `colnames<-`(c("Pro","School","Perso"))

ZIPCode <- ZIPCodeDB %>%
  select(zip_code, gps_lat, gps_lng,name) %>%
  mutate(ID=1, ID=ave(ID, zip_code, FUN=cumsum)) %>%
  filter(ID==1) %>%
  select(-ID)

ZIPCode <- rbind(ZIPCode,
c("LU-2182",49.58317971148099,6.122436170578234, "Luxembourg"),
c("BE-5000",50.4669,4.8675, "Namur"),
c("BE-6840",49.8407,5.4353, "Neufchâteau"),
c("NZ-0632",-36.74421756663356,174.69668408595604, "Auckland"),
c("CH-1010",46.5377,6.6553, "Lausanne"),
c("LU-1137",49.58453333444523,6.138253219045353, "Howald"),
c("CH-1295",46.3072,6.1811, "Lausanne")) %>% unique()

ZIPPoints <- rbind(ZIPDB[1] %>% `colnames<-`(c("Zip")),
      ZIPDB[2] %>% `colnames<-`(c("Zip")),
      ZIPDB[3] %>% `colnames<-`(c("Zip"))) %>%
  table() %>% 
  as.data.frame() %>%
  `colnames<-`(c("zip_code","Freq"))


ZIPPoints$zip_code <- ZIPPoints$zip_code %>% droplevels() %>% as.character()

ZIPToAdd <- ZIPPoints$zip_code[!ZIPPoints$zip_code %in% ZIPCode$zip_code]

ZIPPoints <- ZIPPoints %>% merge(y = ZIPCode, by = "zip_code")

ZIPCode <- ZIPCode %>% select(zip_code, gps_lat, gps_lng)
ZIPCode <- ZIPCode[ZIPCode$zip_code %in% ZIPPoints$zip_code,]

PersoPro <- ZIPDB %>%
  select("Pro","Perso") %>%
  `colnames<-`(c("zip_code","Perso")) %>%
  merge(y = ZIPCode, by = "zip_code") %>%
  `colnames<-`(c("Pro","zip_code","Pro_lat","Pro_lng")) %>% 
  merge(y = ZIPCode, by = "zip_code") %>% 
  `colnames<-`(c("Perso","Pro","Pro_lat","Pro_lng","Perso_lat","Perso_lng")) %>% 
  table() %>%
  as.data.frame() %>% 
  filter(Freq>0)

SchoolPerso <- ZIPDB %>% select("Perso","School") %>% `colnames<-`(c("zip_code","School")) %>%
  merge(y = ZIPCode, by = "zip_code") %>%
  `colnames<-`(c("Perso","zip_code","Perso_lat","Perso_lng")) %>% 
  merge(y = ZIPCode, by = "zip_code") %>% 
  `colnames<-`(c("School","Perso","Perso_lat","Perso_lng","School_lat","School_lng")) %>%
  table() %>% 
  as.data.frame() %>% 
  filter(Freq>0)


SchoolPerso$School_lng <- SchoolPerso$School_lng %>% droplevels() %>% as.character() %>% as.numeric()
SchoolPerso$School_lat <- SchoolPerso$School_lat %>% droplevels() %>% as.character() %>% as.numeric()
SchoolPerso$Perso_lat <- SchoolPerso$Perso_lat %>% droplevels() %>% as.character() %>% as.numeric()
SchoolPerso$Perso_lng <- SchoolPerso$Perso_lng %>% droplevels() %>% as.character() %>% as.numeric()

PersoPro$Pro_lng <- PersoPro$Pro_lng %>% droplevels() %>% as.character() %>% as.numeric()
PersoPro$Pro_lat <- PersoPro$Pro_lat %>% droplevels() %>% as.character() %>% as.numeric()
PersoPro$Perso_lat <- PersoPro$Perso_lat %>% droplevels() %>% as.character() %>% as.numeric()
PersoPro$Perso_lng <- PersoPro$Perso_lng %>% droplevels() %>% as.character() %>% as.numeric()

PersoPro$Width <- PersoPro$Freq %>% normalize(method = "range",range = c(1, 5))
SchoolPerso$Width <- SchoolPerso$Freq %>% normalize(method = "range",range = c(1, 5))
ZIPPoints$Width <- ZIPPoints$Freq %>% normalize(method = "range",range = c(0.5, 1.5))
map('world',
    col="#f2f2f2", fill=TRUE, bg="white", lwd=0.05,
    mar=rep(0,4),border=0, ylim=c(40,55), xlim=c(-10,20)
)
for (i in 1:nrow(SchoolPerso)){
  inter <- gcIntermediate(c(SchoolPerso$School_lng[i],SchoolPerso$School_lat[i]),
                        c(SchoolPerso$Perso_lng[i],SchoolPerso$Perso_lat[i]),
                        n=50, addStartEnd=TRUE, breakAtDateLine=F)
  lines(inter, col=yellow, lwd=SchoolPerso$Width[i])
}
for (i in 1:nrow(PersoPro)){
  inter <- gcIntermediate(c(PersoPro$Pro_lng[i],PersoPro$Pro_lat[i]),
                        c(PersoPro$Perso_lng[i],PersoPro$Perso_lat[i]),
                        n=50, addStartEnd=TRUE, breakAtDateLine=F)
  lines(inter, col=pink, lwd=PersoPro$Width[i])
}
points(x=ZIPPoints$gps_lng, y=ZIPPoints$gps_lat, col=purple, cex=ZIPPoints$Width, pch=20)

ZIPPoints <- ZIPPoints %>%
  mutate(zip_code = substring(zip_code,1,2)) %>% 
  group_by(zip_code) %>%
  summarise(Freq=sum(Freq),
            name=first(name),
            gps_lat=first(gps_lat),
            gps_lng=first(gps_lng)) %>%
  mutate(Width = normalize(Freq, method = "range",range = c(2, 9)))

ZIPPointsCol <- ZIPPoints$Freq %>% unique() %>% sort() %>% as.data.frame() %>% `colnames<-`(c("Freq"))
ZIPPointsCol$Color <- colfunc3(nrow(ZIPPointsCol))
ZIPPoints <- merge(x = ZIPPoints, y = ZIPPointsCol, by = "Freq")

map('world',
    col="#f2f2f2", fill=TRUE, bg=pink, lwd=0.05,
    mar=rep(0,4),border=0, ylim=c(40,55), xlim=c(-15,21)
)
points(x=ZIPPoints$gps_lng, y=ZIPPoints$gps_lat, col=ZIPPoints$Color, cex=ZIPPoints$Width, pch=20)

BirthYear <- FormDB$`Your year of birth:` %>% table() %>% as.data.frame()

Year <- (BirthYear$. %>% droplevels() %>% as.character() %>% as.numeric() %>% min()):(BirthYear$. %>% droplevels() %>% as.character() %>% as.numeric() %>% max()) %>% as.data.frame()

Year <- Year[!Year$. %in% BirthYear$.,] %>% as.data.frame() %>% mutate(Freq=NA)

BirthYear$. <- BirthYear$. %>% droplevels() %>% as.character() %>% as.numeric()

BirthYear <- rbind(BirthYear,Year) %>% arrange(.)

BirthYear$Year <- ((BirthYear$.*2) %>% round(-1))/2

BirthYear <- BirthYear %>% group_by(Year) %>% summarise(Freq = sum(Freq, na.rm=T))


Age_graph <- ggplot(BirthYear, aes(x = Year, y = Freq))+
  geom_bar(stat = "summary", fun = "mean", fill=pink)+
  geom_smooth(col = yellow, method = lm, formula = y ~ splines::bs(x, 2), se = FALSE)+
  geom_text(aes(label = Freq),
            size=3,
            hjust=0.5,
            vjust=-1,
            check_overlap = T)+
  ylim(0,max(BirthYear$Freq)+4)+
  labs(title="Distribution of respondents' years of birth",
       subtitle=paste0("1998 corresponds to the year of birth of the majority of the students of my promotion"),
       y="Frequency", x="Year",
       caption = SourceText)+
  theme(text=element_text(size=12, family="AvertaPE-Regular"),
        panel.background = element_blank(),
        legend.position = "right",
        legend.background = element_blank(),
        axis.line = element_line(colour = purple),
        plot.title = element_text(size = 15, family = "AvertaPE-Black", color = purple),
        plot.caption = element_text(size = 8, color = blue))

ggsave("Age.png", Age_graph)

Age_graph

MatrixName <- matrix(data=NA, nrow = nrow(FormDB), ncol = nrow(FormDB)) %>%
  as.data.frame() %>% 
  `colnames<-`(FormDB$ID) %>% 
  `rownames<-`(FormDB$ID)

for (col in 1:ncol(MatrixName)){
  for (row in 1:nrow(MatrixName)){
    MatrixName[row,col] <-
      FormDB$LastName[FormDB$ID==rownames(MatrixName[row,])]==FormDB$LastName[FormDB$ID==colnames(MatrixName)[col]]
  }
}

MatrixLastName <- MatrixName %>% mutate(from=rownames(MatrixName))
MatrixLastName <- MatrixLastName[,c(ncol(MatrixLastName),1:(ncol(MatrixLastName)-1))] %>%
  as.data.frame() %>%
  gather(key="to", value="value", -1) %>%
  mutate(to = gsub("\\.", " ",to)) %>%
  na.omit() %>% 
  filter(value==TRUE)

for (col in 1:ncol(MatrixName)){
  for (row in 1:nrow(MatrixName)){
    MatrixName[row,col] <-
      FormDB$`Name of your company:`[FormDB$ID==rownames(MatrixName[row,])]==FormDB$`Name of your company:`[FormDB$ID==colnames(MatrixName)[col]]
  }
}

MatrixPro <- MatrixName %>% mutate(from=rownames(MatrixName))
MatrixPro <- MatrixPro[,c(ncol(MatrixPro),1:(ncol(MatrixPro)-1))] %>%
  as.data.frame() %>%
  gather(key="to", value="value", -1) %>%
  mutate(to = gsub("\\.", " ",to)) %>%
  na.omit() %>% 
  filter(value==TRUE)

for (col in 1:ncol(MatrixName)){
  for (row in 1:nrow(MatrixName)){
    MatrixName[row,col] <-
      FormDB$`Name of your recently attended school:`[FormDB$ID==rownames(MatrixName[row,])]==FormDB$`Name of your recently attended school:`[FormDB$ID==colnames(MatrixName)[col]]
  }
}

MatrixSchool <- MatrixName %>% mutate(from=rownames(MatrixName))
MatrixSchool <- MatrixSchool[,c(ncol(MatrixSchool),1:(ncol(MatrixSchool)-1))] %>%
  as.data.frame() %>%
  gather(key="to", value="value", -1) %>%
  mutate(to = gsub("\\.", " ",to)) %>%
  na.omit() %>% 
  filter(value==TRUE, from!=to)

MatrixLastName$value <- "Family"
MatrixSchool$value <- "School"
MatrixPro$value <- "Pro"

MatrixPerso <- FormDB %>%
  select(ID, Link) %>%
  filter(!is.na(Link)) %>%
  `colnames<-`(c("from","to")) %>% 
  mutate(value = "Perso")

Top_Network <- rbind(MatrixLastName,MatrixSchool,MatrixPro,MatrixPerso)
Top_Network <- Top_Network[Top_Network$from!=Top_Network$to,]


Top_Network_Top <- Top_Network %>% select(from,to) %>% unique()
Top_Network_Top <- c(Top_Network_Top$from,Top_Network_Top$to) %>% table() %>% as.data.frame() %>% arrange(desc(Freq))

p <- simpleNetwork(Top_Network %>% select(from,to), height="100px", width="100px",        
        Source = 1,             # column number of source
        Target = 2,             # column number of target
        linkDistance = 10,      # distance between node. Increase this value to have more space between nodes
        charge = -900,          # numeric value indicating either the strength of the node repulsion (negative value) or attraction (positive value)
        fontSize = 14,          # size of the node names
        fontFamily = font,   # font og node names
        linkColour = purple,    # colour of edges, MUST be a common colour for the whole graph
        nodeColour = pink,     # colour of nodes, MUST be a common colour for the whole graph
        opacity = 1,        # opacity of nodes. 0=transparent. 1=no transparency
        zoom = T              # Can you zoom on the figure?
        )

p
library(igraph)
## Warning: package 'igraph' was built under R version 4.1.2
## 
## Attaching package: 'igraph'
## The following object is masked from 'package:BBmisc':
## 
##     normalize
## The following objects are masked from 'package:dplyr':
## 
##     as_data_frame, groups, union
## The following objects are masked from 'package:purrr':
## 
##     compose, simplify
## The following object is masked from 'package:tidyr':
## 
##     crossing
## The following object is masked from 'package:tibble':
## 
##     as_data_frame
## The following objects are masked from 'package:stats':
## 
##     decompose, spectrum
## The following object is masked from 'package:base':
## 
##     union
links <- Top_Network %>% select(from,to)

network <-
  graph.data.frame(links,
                   vertices = unique(FormDB$ID),
                   directed = TRUE)

plot(
  as.undirected(network),
  layout = layout.kamada.kawai(network),
  vertex.size = 3,
  vertex.label = FormDB$ID,
  vertex.label.color = purple,
  vertex.label.dist = 1,
  edge.arrow.size = 0.2,
  vertex.color = pink
)

UTAUTAnalysis <- FormDB[6:29] %>% t() %>% as.data.frame()
rownames(UTAUTAnalysis) <- 1:nrow(UTAUTAnalysis)

UTAUT_List <- UTAUT_List %>% as.data.frame() %>% mutate(`1`=1, `2`=2, `3`=3, `4`=4, `5`=5)

for (i in 1:nrow(UTAUT_List)){
  UTAUT_List$Mean[i] <- UTAUTAnalysis[i,] %>% unlist() %>% mean()
  for (j in 1:5){
    UTAUT_List[i,j+2] <- (UTAUTAnalysis[i,] %>%
                            unlist() %>%
                            table() %>%
                            as.data.frame() %>%
                            `colnames<-`(c("Value","Freq")) %>%
                            filter(Value==j))[2] %>% as.numeric()
  }
}

colnames(UTAUT_List)[1:2] <- c("Category","Question")

UTAUT_List$Category <- UTAUT_List$Category %>% str_squish()
UTAUT_List$Question <- UTAUT_List$Question %>% str_remove_all("\\]")

UTAUT_Group <- UTAUT_List %>% 
  group_by(Category) %>% 
  summarise(Mean = mean(Mean),
            `1`=sum(`1`,na.rm=T),
            `2`=sum(`2`,na.rm=T),
            `3`=sum(`3`,na.rm=T),
            `4`=sum(`4`,na.rm=T),
            `5`=sum(`5`,na.rm=T))

UTAUT_Radar <- UTAUT_Group %>% select(1,2) %>% t()
UTAUT_Radar[1,] <- c("Behavior","Effort","Facilitating","Enjoyment","Performance","Social","Trust")
colnames(UTAUT_Radar) <- UTAUT_Radar[1,] %>% str_replace(" / ","/")  %>% str_replace(" ","\n")
UTAUT_Radar <- UTAUT_Radar[2,] %>% t() %>% as.data.frame()
UTAUT_Radar[1,] <- ((UTAUT_Radar[1,] %>% as.numeric())/5) %>% round(2)
UTAUT_Radar[2,] <- (c(3.224,2.535,3.348,3.264,3.1,3.325,3.163)/5) %>% round(2)
UTAUT_Radar[,1:7] <- sapply(UTAUT_Radar[,1:7], as.numeric)
UTAUT_Radar <- cbind(c("Thesis Results","Triasesiarta Nur Results"),UTAUT_Radar[1:7])
colnames(UTAUT_Radar)[1] <- "Name"



library(ggradar)

Skill_radar_graph <- UTAUT_Radar %>%
  ggradar(font.radar = font,
          grid.label.size = 4,  # Affects the grid annotations (0%, 50%, etc.)
          axis.label.size = 4,
          group.point.size = 5,   # Simply the size of the point 
          group.colours = c(yellow, pink))+
  labs(title = paste("Comparison of the results obtained by the UTAUT Model"),
       subtitle = "between my study and the literature review",
       caption = SourceText)+
  theme(text=element_text(size=12, family="AvertaPE-Regular"),
        legend.position = c(-0.1,-0.025),
        legend.justification = "left",
        legend.text = element_text(size = 10, family = font),
        legend.key = element_rect(fill = NA, color = NA),
        panel.background = element_blank(),
        legend.background = element_blank(),
        plot.title = element_text(size = 15, family = "AvertaPE-Black", color = purple),
        plot.caption = element_text(size = 8, color = blue))

ggsave("Comparison radar.png", Skill_radar_graph)

Skill_radar_graph

UTAUT_Group2 <- rbind(UTAUT_Group %>% select(1,3) %>% `colnames<-`(c("Category","Freq")) %>% mutate(Rate = 1),
                      UTAUT_Group %>% select(1,4) %>% `colnames<-`(c("Category","Freq")) %>% mutate(Rate = 2),
                      UTAUT_Group %>% select(1,5) %>% `colnames<-`(c("Category","Freq")) %>% mutate(Rate = 3),
                      UTAUT_Group %>% select(1,6) %>% `colnames<-`(c("Category","Freq")) %>% mutate(Rate = 4),
                      UTAUT_Group %>% select(1,7) %>% `colnames<-`(c("Category","Freq")) %>% mutate(Rate = 5)) %>% 
  mutate(Rate = as.character(Rate))

library(ggridges)

UTAUT_Group_graph <- ggplot(UTAUT_Group2, aes(x = Category, y = Freq, fill = Rate, group = Rate)) +
  geom_col(position = "dodge")+
  coord_flip()+
  scale_fill_manual(values=colfunc2(5))+
  labs(title="Model UTAUT analysis on a scale of 1 to 5",
       subtitle=paste0("1998 corresponds to the year of birth of the majority of the students of my promotion"),
       y="Rate Frequency", x=element_blank(),
       caption = SourceText)+
  theme(text=element_text(size=12, family="AvertaPE-Regular"),
        panel.background = element_blank(),
        legend.position = "right",
        legend.background = element_blank(),
        axis.line = element_line(colour = purple),
        plot.title = element_text(size = 15, family = "AvertaPE-Black", color = purple),
        plot.caption = element_text(size = 8, color = blue))

ggsave("UTAUT Overview.png", UTAUT_Group_graph)

UTAUT_Group_graph

UTAUT_List$Category <- UTAUT_List$Category %>% str_replace_all(" / "," and ")

for (i in 1:nrow(UTAUT_List)){
  UTAUT_List2 <- UTAUT_List %>%
    filter(Category==UTAUT_List$Category[i])

  UTAUT_graph <- rbind(
    UTAUT_List2 %>% select(1,2,3) %>% `colnames<-`(c("Category","Question","Freq")) %>% mutate(Rate = "1"),
    UTAUT_List2 %>% select(1,2,4) %>% `colnames<-`(c("Category","Question","Freq")) %>% mutate(Rate = "2"),
    UTAUT_List2 %>% select(1,2,5) %>% `colnames<-`(c("Category","Question","Freq")) %>% mutate(Rate = "3"),
    UTAUT_List2 %>% select(1,2,6) %>% `colnames<-`(c("Category","Question","Freq")) %>% mutate(Rate = "4"),
    UTAUT_List2 %>% select(1,2,7) %>% `colnames<-`(c("Category","Question","Freq")) %>% mutate(Rate = "5")) %>%
    ggplot(aes(x = Question, y = Freq, fill = Rate, group = Rate)) +
      geom_col(position = "dodge")+
      scale_x_discrete(labels = function(y) str_wrap(y, width = 20))+
      coord_flip()+
      scale_fill_manual(values=colfunc2(5))+
      labs(title="Model UTAUT analysis on a scale of 1 to 5",
           subtitle=paste0(UTAUT_List2[1,1]),
           y="Rate Frequency", x=element_blank(),
           caption = SourceText)+
      theme(text=element_text(size=12, family="AvertaPE-Regular"),
            panel.background = element_blank(),
            legend.position = "right",
            legend.background = element_blank(),
            axis.line = element_line(colour = purple),
            plot.title = element_text(size = 15, family = "AvertaPE-Black", color = purple),
            plot.caption = element_text(size = 8, color = blue))
  ggsave(paste0(UTAUT_List$Category[i],".png"), UTAUT_graph)
}
## Saving 7 x 5 in image
## Saving 7 x 5 in image
## Saving 7 x 5 in image
## Saving 7 x 5 in image
## Warning: Removed 2 rows containing missing values (geom_col).
## Saving 7 x 5 in image
## Warning: Removed 2 rows containing missing values (geom_col).
## Saving 7 x 5 in image
## Warning: Removed 2 rows containing missing values (geom_col).
## Saving 7 x 5 in image
## Saving 7 x 5 in image
## Saving 7 x 5 in image
## Saving 7 x 5 in image
## Saving 7 x 5 in image
## Saving 7 x 5 in image
## Saving 7 x 5 in image
## Saving 7 x 5 in image
## Saving 7 x 5 in image
## Saving 7 x 5 in image
## Saving 7 x 5 in image
## Saving 7 x 5 in image
## Saving 7 x 5 in image
## Saving 7 x 5 in image
## Saving 7 x 5 in image
## Saving 7 x 5 in image
## Saving 7 x 5 in image
## Saving 7 x 5 in image