---
title: "Base Study 1 --- Full Analysis"
author: "Gian Luca Liehner"
date: "`r format(Sys.Date(), '%B %d, %Y')`"
format:
  html:
    toc: true
    toc-location: left
editor: source
---

```{r setup}
#| message: false
#| echo: false
## Global options
knitr::opts_chunk$set(cache = TRUE, message = TRUE)
library(haven) # Reads SPSS
library(tidyverse) # Data manipulation
library(questionr) # Frequency tables
library(kableExtra) # Nice kable tables
library(janitor) # Make databases look nice
library(careless) # Longstrings
library(psych) # Scale manipulation
library(Hmisc) # Social data manipulation
library(corrplot) # Correlation plots
library(likert) # Visualising likert scales

# Theme
theme_dissertation <- function () { 
    theme_minimal(base_size=12) +
        theme(
            panel.background  = element_blank(),
            legend.background = element_rect(fill="transparent", colour=NA),
            legend.key = element_rect(fill="transparent", colour=NA), 
            text=element_text(size=12,  family="Avenir"),
            plot.background = element_rect(fill = "transparent", color = NA),
            axis.title.y = element_text(margin = margin(t = 0, r = 20, b = 0, l = 0), size = 12),
            axis.title.x = element_text(margin = margin(t = 10, r = 0, b = 0, l = 0), size = 12),
            plot.title = element_text(margin=margin(0,0,10,0)),
            legend.margin=margin(l = 10,),
            #panel.grid.major = element_line(colour = "#565555", size = .25)
            plot.caption = element_text(size=8, color = "#333333", face = "italic"),
            plot.subtitle = element_text(size=8, color = "#333333")
        )
}

# Colours
colour_dis <- c(
  teal        = "#006d77",
  mint        = "#83c5be",
  off_white   = "#edf6f9",
  peach       = "#ffddd2",
  clay        = "#e29578",
  blue        = "#457b9d",
  blue_light  = "#a8dadc",
  pink        = "#ef476f",
  pink_light  = "#ffb4c8"
)
```

# Overview
## Loading the data from file

```{r message=FALSE}
raw_data <- read_csv("raw_data_values.csv", show_col_types = TRUE)
# removing first to meta data rows
raw_data <- raw_data %>% slice(-(1:2)) # cleaning names
# renaming varialbes to camel case 
raw_data <- clean_names(raw_data, "snake")
```

## Selecting relevant data 
```{r}
data <- raw_data %>% select(response_id,
                            progress, 
                            duration = duration_in_seconds, 
                            alter:taetigkeit, 
                            kusiv3_1:risikobereitschaft_1, 
                            ati_1:sensitivity_threat_5,
                            general_attitude_ki_1:nutzungsbereitschaft_11)

n = data %>% tally()
```

```{r}
## Converting to numeric 
data <- data  %>%  mutate(across(-response_id, ~ as.numeric(.x)))

# recoding variables to factor
data$geschlecht <- factor(data$geschlecht, 
                    levels = c(1, 2), 
                    labels = c("male", "female"))

data$taetigkeit <- factor(data$taetigkeit, 
                    levels = c(1, 2,3,4,5,6,7,8), 
                    labels = c("School student",
                      "University student",
                      "Apprentice/Trainee",
                      "Employee",
                      "Self-employed",
                      "Retired",
                      "Homemaker",
                      "Currently unemployed"))

data$ausbildung <- factor(data$ausbildung, 
                    levels = c(1,2,3,4), 
                    labels = c("No degree yet",
                      "Secondary school degree (e.g., Hauptschule, Realschule, etc.)",
                      "High school diploma (e.g Abitur)",
                      "Higher education degree (Bachelor, Master, PhD, etc.)"))
                    
```

Initial dataset before data cleaning N = `r n`

---

# Date cleaning

## Drop NAs in demographics

```{r}
data <- data %>% drop_na(c(alter, 
                           geschlecht, 
                           ausbildung, 
                           taetigkeit
                           )
                         )
```

Dropped cases `r data %>% tally()-n`
`r  n <- data %>% tally()`

## Filtering out minors

```{r}
data <- data %>% filter(!alter < 18)
```

Dropped cases `r data %>% tally()-n`
`r  n <- data %>% tally()`

## Filtering out NAs in personality traits

```{r}
data <- data %>% drop_na(starts_with("kusiv"), 
                         risikobereitschaft_1, 
                         starts_with("ati"), 
                         starts_with("dangerous"), 
                         starts_with("sensitivity")
                         )
```

Dropped cases `r data %>% tally()-n`
`r  n <- data %>% tally()`

## Removing speeders

```{r}
median_completion_time <- median(data$duration)
data <- data %>% filter(!duration < median_completion_time/2) 
```

Dropped cases `r data %>% tally()-n`
`r  n <- data %>% tally()`

## Checking for long-string cases

```{r}
# Interpersonal trust
data %>% select(starts_with("kusiv")) %>% longstring() -> data$kusiv_ls
data %>% filter(!kusiv_ls == 3) -> data
# Sensitivity to threat 
data %>% select(starts_with("sens")) %>% longstring() -> data$sensitivity_ls
data %>% filter(!sensitivity_ls== 5) -> data
# Believe in a dangerous world 
data %>% select(starts_with("dangerous")) %>% longstring() -> data$dangerous_ls
data %>% filter(!dangerous_ls == 10) -> data
# Believe in a ati
data %>% select(starts_with("ati")) %>% longstring() -> data$ati_ls
data %>% filter(!ati_ls == 10) -> data
```

Dropped cases `r data %>% tally()-n`
`r  n <- data %>% tally()`

## Calculating Mahalanobis Distance (D) and flag potential outliers.

```{r}
mahad_analysis <- data %>% select(kusiv3_1:risikobereitschaft_1, 
                                  ati_1:sensitivity_threat_5) %>% 
  mahad(plot = TRUE, flag = TRUE, confidence = 0.99, na.rm = TRUE)
data$mahad_num <- mahad_analysis$d_sq
data$mahad_flag <- mahad_analysis$flagged

data <- data %>% filter(mahad_flag == FALSE)
```

Dropped cases `r data %>% tally()-n`
`r  n <- data %>% tally()`

---

**Final N** = `r data %>% tally()`

# Sample description

## Age
```{r echo=FALSE}
psych::describe(data$alter, fast = TRUE) %>% kable(caption = "Descriptives for age", digits = 2, row.names = FALSE) %>%  kable_material()
data %>% 
  ggplot +
  aes(alter) +
  geom_histogram(binwidth = 1, fill=colour_dis["mint"], color=colour_dis["teal"], size=.3) +
  geom_density(aes(y = ..density..*nrow(data)), color=colour_dis["pink"]) +
  geom_vline(xintercept = mean(data$alter), linetype="dotted", color = colour_dis["pink"], size=1.5) +
  labs(x="Age", title = "Age histrogram", y="Absolute count", caption = "Blue dotted line represents mean, and pink solid line represents density") +
  theme_dissertation()
```

## Gender

```{r echo=FALSE}
questionr::freq(data$geschlecht, sort = "dec") %>% kable(caption = "Frequency table for gender", digits = 2) %>%  kable_material()
```

## Occupation

```{r echo=FALSE}
questionr::freq(data$taetigkeit, sort = "dec") %>% kable(caption = "Frequency table for occupation", digits = 2) %>%  kable_material()
```

## Education

```{r echo=FALSE}
questionr::freq(data$ausbildung, sort = "dec") %>% kable(caption = "Frequency table for education", digits = 2) %>%  kable_material()
```

# Personality traits

## Interpersonal trust score

```{r echo=FALSE}
kusiv_items <- data %>% select(starts_with("kusiv"))
kusiv_keys <-  list(kusiv_scores = c(
  "kusiv3_1",
  "-kusiv3_2",
  "kusiv3_3"
  ))
kusiv_scores <- psych::scoreItems(kusiv_keys, kusiv_items, min = 1, max = 6)  

data <- data  %>% bind_cols(kusiv_scores$scores %>% as_tibble())
kusiv_scores$scores %>%  psych::describe(fast = TRUE, ranges = FALSE) %>% kable(caption = "Average interpersonal trust score", digits = 2,  row.names = FALSE) %>%  kable_material()
```

The reliability for the *interpersonal trust scale* is `r round(kusiv_scores$alpha, 2)`.

## Risk disposotion

```{r}
#| echo: false
data$risikobereitschaft_1 %>%  psych::describe(fast = TRUE, ranges = FALSE) %>% kable(caption = "Average risk disposition score", digits = 2,  row.names = FALSE) %>%  kable_material()
```


## Believe in a dangerous world score

```{r echo=FALSE}
bdws_items <- data %>% select(starts_with("dangerous"))
bdws_keys <-  list(bdws_scores = c(
  "-dangerous_world_1",
  "dangerous_world_2",
  "dangerous_world_3",
  "-dangerous_world_4",
  "-dangerous_world_5",
  "dangerous_world_6",
  "-dangerous_world_7",
  "dangerous_world_8",
  "-dangerous_world_9",
  "dangerous_world_10"
  ))
bdws_scores <- psych::scoreItems(bdws_keys, bdws_items, min = 1, max = 6)  

data <- data  %>% bind_cols(bdws_scores$scores %>% as_tibble())
bdws_scores$scores %>%  psych::describe(fast = TRUE, ranges = FALSE) %>% kable(caption = "Average believe in a dangerous world score", digits = 2,  row.names = FALSE) %>%  kable_material()
```

The reliability for the *dangerous world scale* is `r round(bdws_scores$alpha, 2)`.

## Sensitivity to threat scale

```{r echo=FALSE}
sensitivity_items <- data %>% select(sensitivity_threat_1:sensitivity_threat_5)
sensitivity_keys <-  list(sensitivity_scores = c(
  "sensitivity_threat_1", 
  "-sensitivity_threat_2",
  "-sensitivity_threat_3",
  "sensitivity_threat_4",
  "-sensitivity_threat_5"))
sensitivity_scores <- psych::scoreItems(sensitivity_keys, sensitivity_items, min = 1, max = 6)  

data <- data  %>% bind_cols(sensitivity_scores$scores %>% as_tibble())
sensitivity_scores$scores %>%  psych::describe(fast = TRUE, ranges = FALSE) %>% kable(caption = "Average **sensitivity to threat** score", digits = 2,  row.names = FALSE) %>%  kable_material()
```

The reliability for the *sensitivity to thread scale* is `r round(sensitivity_scores$alpha, 2)`.


## Affinity for technology 

```{r echo=FALSE}
ati_items <- data %>% select(ati_1:ati_10)
ati_keys <-  list(ati_scores = c(
  "ati_1",
  "ati_2",
  "-ati_3",
  "ati_4",
  "ati_5",
  "-ati_6",
  "ati_7",
  "-ati_8",
  "ati_9",
  "ati_10"
  ))
ati_scores <- psych::scoreItems(ati_keys, ati_items, min = 1, max = 6)  

data <- data  %>% bind_cols(ati_scores$scores %>% as_tibble())
ati_scores$scores %>%  psych::describe(fast = TRUE, ranges = FALSE) %>% kable(caption = "Average affitinity for technology score", digits = 2,  row.names = FALSE) %>%  kable_material()
```

The reliability for the *affinity for technology* is `r round(ati_scores$alpha, 2)`.

# Desriptives & exploration

## Generall attitudes towards AI

### Exploratory factor analysis

```{r}
generall_attitude_items <- data %>% select(general_attitude_ki_3, general_attitude_ki_4, general_attitude_ki_5, general_attitude_ki_6, affectiv_evaluation_ki_1, affectiv_evaluation_ki_2, affectiv_evaluation_ki_3, affectiv_evaluation_ki_4, affectiv_evaluation_ki_5) %>% drop_na()

# Correlation and covariance between the items
cortest.bartlett(R=cor(generall_attitude_items), n=133, )
# common variance between the items
KMO(generall_attitude_items)

#Find out number of factors
fa.parallel(generall_attitude_items, fa="fa", fm="ml", show.legend =F)


efa_results <- fa(generall_attitude_items, nfactors = 2, fm="minres", rotate = "oblimin")

efa_results

```

**Different factors could not be found!**

---

### Reliability for general attitudes

```{r}
#| echo: false
data %>% select(general_attitude_ki_3, general_attitude_ki_4, general_attitude_ki_5, general_attitude_ki_6, affectiv_evaluation_ki_1, affectiv_evaluation_ki_2, affectiv_evaluation_ki_3, affectiv_evaluation_ki_4) -> generall_attitude_items

generall_attitude_keys <-  list(general_attitude_scores = c(
  "general_attitude_ki_3", 
  "-general_attitude_ki_4", 
  "-general_attitude_ki_5", 
  "-general_attitude_ki_6", 
  "affectiv_evaluation_ki_1", 
  "affectiv_evaluation_ki_2", 
  "affectiv_evaluation_ki_3", 
  "affectiv_evaluation_ki_4"
  ))
general_attitudes_scores <- psych::scoreItems(generall_attitude_keys, generall_attitude_items, min = 1, max = 6)  

data <- data  %>% bind_cols(general_attitudes_scores$scores %>% as_tibble())
general_attitudes_scores$scores %>%  psych::describe(fast = TRUE, ranges = FALSE) %>% kable(caption = "Average attitude towards AI score", digits = 2,  row.names = FALSE) %>%  kable_material()



```
The reliability for the *generall attitude towards AI scale* is `r round(general_attitudes_scores$alpha, 2)`.




## General associations

```{r}
#| echo: false
#| message: false
data %>% select(starts_with("vorurteile_ki")) -> myths_likert_data
library(likert)
library(sjPlot)
library(sjmisc)
likert_plot_myths <- plot_likert(myths_likert_data, 
                           values = "sum.outside", 
                           show.prc.sign = TRUE, 
                           wrap.labels = 64, 
                           title = "Likert scale distributions for general associations towards AI", 
                           reverse.scale = TRUE, 
                           axis.titles=rev(c("Level of agreement", "Statements about artificial intelligence")), 
                           axis.labels=c("2. AI as a tool",
                                         "9. AI as an artificial player in a computer game",
                                         "5. AI as a replacement of the human workforce",
                                         "1. AI as an independent, adaptive system", 
                                         "4. AI as something unknown",
                                         "6. AI as science fiction robots", 
                                         "3. AI is unaccessible and difficult to understand", 
                                         "10. AI as a threat to humanity",
                                         "11. AI will take control of the world",
                                         "8. AI will make people stupid and not be able to think for themselves",
                                         "7. AI will never resemble the human brain"

                          ), 
                           sort.frq = "pos.asc", 
                           show.n = FALSE) + 
  theme_dissertation() +
  scale_fill_manual(labels=c("strongly disagree", "disagree", "rather disagree", "rather agree", "agree", "strongly agree"), 
                    values=c("#ed6976", "#f18c90", "#f5acac", "#a6d5c1", "#81c6ab", "#50b796")) + 
  theme(legend.position="bottom", text = element_text(size = 20)) 

likert_plot_myths

ggsave('./exports/likert_plot_myths_and_prejudices.png', width = 14, height = 9, units = "cm", scale = 2.5)
ggsave('./exports/likert_plot_myths_and_prejudices.svg', width = 14, height = 9, units = "cm", scale = 2.5)

```

## Chances

```{r}
#| echo: false
#| message: false
data %>% select(chancen_risiken_ki_5, chancen_risiken_ki_6, chancen_risiken_ki_14, chancen_risiken_ki_19, chancen_risiken_ki_20, chancen_risiken_ki_21) -> chances_likert_data

likert_plot_chances <- plot_likert(chances_likert_data, 
                           values = "sum.outside",
                           show.prc.sign = TRUE,  
                           wrap.labels = 64, 
                           title = "Likert scale distributions for perceived chances of AI applications", 
                           reverse.scale = TRUE, 
                           axis.titles=rev(c("Level of agreement", "Statements about artificial intelligence")),
                           axis.labels=c("5. Enhancement of life quality", 
                                        "2. Automation of processes to reduce work time", 
                                        "4. Bring higher standart of living", 
                                        "3. Support people in day to day life",
                                        "6. The safe use of AI",
                                        "1. Support people in a general way"
                                        ), 
                           sort.frq = "pos.asc",
                           show.n = FALSE) + 
  theme_dissertation()+
  scale_fill_manual(labels=c("strongly disagree", "disagree", "rather disagree", "rather agree", "agree", "strongly agree"),
                    values=c("#ed6976", "#f18c90", "#f5acac", "#a6d5c1", "#81c6ab", "#50b796"))+
  theme(legend.position="bottom", text = element_text(size = 20)) # Legende unten

likert_plot_chances 

ggsave('./exports/likert_plot_chances_ai.png', width = 14, height = 9, units = "cm", scale = 2.5) # Speichern der Grafik als PNG
ggsave('./exports/likert_plot_chances_ai.svg', width = 14, height = 9, units = "cm", scale = 2.5) # Speichern der Grafik als PNG
```
## Risks of AI
```{r echo=FALSE, message=FALSE, warning=FALSE}
data %>% select(starts_with("chancen"), -chancen_risiken_ki_5, -chancen_risiken_ki_6, -chancen_risiken_ki_14, -chancen_risiken_ki_19, -chancen_risiken_ki_20, -chancen_risiken_ki_21) -> risk_likert_data

likert_plot_risks <- plot_likert(risk_likert_data, 
                           values = "sum.outside", 
                           show.prc.sign = TRUE, 
                           wrap.labels = 64, 
                           title = "Likert scale distributions for perceived risks of AI applications", 
                           reverse.scale = TRUE, 
                           axis.titles=c("Level of agreement", "Statements about artificial intelligence"), 
                           axis.labels=c("4. AI is not mature enough to be used in day-to-day life",
                                         "5. Legal basis is not strong enough for AU to be used everyday",
                                         "9.Irresponsable management of private data",
                                         "6. Privacy concerns",
                                         "8. Fear of espionage",
                                         "16. AI threatens human existance",
                                         "1. AI abused to control people",
                                         "7. Lack of understandability of the decisions of AI",
                                         "13. AI will not reliably execute commands",
                                         "14. AI takes a life of its own and causes harm in the process",
                                         "11. General risk for society",
                                         "15. AI will control us",
                                         "12. Loss of control",
                                         "2. People will become dependent on AI",
                                        "10. Reduction of human interaction through AI",
                                         "3. AI will be hacked by unauthorized people leading to a security risk"
                           ), 
                           sort.frq = "pos.asc", 
                           show.n = FALSE) + 
  theme_dissertation() +
  scale_fill_manual(labels=c("strongly disagree", "disagree", "rather disagree", "rather agree", "agree", "strongly agree"), 
                    values=c("#ed6976", "#f18c90", "#f5acac", "#a6d5c1", "#81c6ab", "#50b796")) + 
  theme(legend.position="bottom", text = element_text(size = 20)) 

likert_plot_risks

ggsave('./exports/likert_plot_risk.svg', width = 14, height = 9, units = "cm", scale = 2.5)
ggsave('./exports/likert_plot_risk.svg', width = 14, height = 9, units = "cm", scale = 2.5)

```
# Target exploration 
## Semantic differential
```{r}
#| echo: false
left_labels <- c(
  "unfamiliar",
  "old-fashioned",
  "conventional",
  "boring",
  "dull",
  "unfriendly",
  "opaque",
  "dangerous",
  "uncontrollable",
  "unreliable",
  "unintelligent",
  "unpredictable",
  "unimaginative"
)
right_labels <- c(
  "familiar",
  "modern",
  "innovative",
  "interesting",
  "exciting",
  "friendly",
  "transparent",
  "harmless",
  "controllable",
  "reliable",
  "intelligent",
  "predictable",
  "creative"
)
data %>% select(starts_with("sem_diff"), response_id) %>% pivot_longer(cols = starts_with("sem_diff")) %>%  group_by(name) %>% mutate(value_centered = 8 -value - 4)%>% summarise(mean_pos = mean(value_centered, na.rm=TRUE), sd_pos = sd(value, na.rm = TRUE)) %>% mutate(item_num = as.numeric(sub("sem_diff_", "", name))) %>% arrange(item_num) %>% 
  mutate(
      side  = if_else(mean_pos >= 0, "right", "left"),
      nudge = if_else(side == "right",  0.15, -0.50),
      nudge_sd = if_else(side == "right",  0.45,-0.10),
      hjust = if_else(side == "right",  0, 1),
    ) -> sem_diff_plot

  ggplot(data = sem_diff_plot, aes(mean_pos,fct_reorder(name, item_num), group = 1)) +
  geom_segment(aes(x = 0, xend = mean_pos, yend = name), linewidth = 3, colour=colour_dis[6]) +
  scale_x_continuous(breaks = -3:3, limits = c(-3,3)) +
  geom_text(aes(x = mean_pos + nudge, label = round(mean_pos,2), hjust = hjust), vjust = 0.5, size = 3.2) +
  geom_text(aes(x = mean_pos + nudge_sd, label = paste0("±", round(sd_pos, 2)),hjust = hjust), vjust = 0.5, size = 2.5, colour="#333333", alpha=0.75) +
  #geom_text(aes(x = 3, label = right_labels),hjust = 0, size = 3.2,) +
  geom_text(data = sem_diff_plot, aes(x = Inf, y = forcats::fct_reorder(name, item_num), label = right_labels), hjust = 0, size = 3.2, inherit.aes = FALSE) +
  scale_y_discrete(labels = left_labels) +
  geom_vline(xintercept = 0, linewidth = 0.5, color = colour_dis[9]) +
  annotate("text", x = 0, y = 0, label = "neutral point", vjust = 3.2, size=3, color=colour_dis[9]) +
  coord_cartesian(clip = "off", expand = TRUE) +
  labs(title= "Affective evaluation of AI by adjective pairs", x="Evaluation scale ranging from 1 to 7", y="Adjective pairs", caption="Standart deviation adjacent to mean value precedet by '±'") +
  
  theme_dissertation() +
  theme(plot.margin = margin(5.5, 80, 5.5, 5.5))

  ggsave('./exports/sem_diff.png', width = 14, height = 9, units = "cm", scale = 1.5)
  ggsave('./exports/sem_diff.svg', width = 14, height = 9, units = "cm", scale = 1.5)
```

## Trust & use intention

### Trust in AI

```{r echo=FALSE}

trust_ai_items <- data %>% select(starts_with("vertrauen_ki"))
trust_ai_keys <-  list(trust_ai_scores = c(
  "vertrauen_ki_1",
  "-vertrauen_ki_2",
  "vertrauen_ki_3",
  "-vertrauen_ki_4",
  "-vertrauen_ki_5"
  ))
trust_ai_scores <- psych::scoreItems(trust_ai_keys, trust_ai_items, min = 1, max = 6)  

data <- data  %>% bind_cols(trust_ai_scores$scores %>% as_tibble())
trust_ai_scores$scores %>%  psych::describe(fast = TRUE, ranges = FALSE) %>% kable(caption = "Average *trust in AI score", digits = 2,  row.names = FALSE) %>%  kable_material()
```

The reliability for the *trust in AI* is `r round(trust_ai_scores$alpha, 2)`.

## Use intention

```{r echo=FALSE}
use_intention_items <- data %>% select(nutzungsbereitschaft_3, nutzungsbereitschaft_4, nutzungsbereitschaft_5, nutzungsbereitschaft_7, nutzungsbereitschaft_9, general_attitude_ki_1)
use_intention_keys <-  list(use_intention_scores = c(
  "nutzungsbereitschaft_3",
  "-nutzungsbereitschaft_4",
  "nutzungsbereitschaft_5",
  "-nutzungsbereitschaft_7",
  "nutzungsbereitschaft_9",
  "general_attitude_ki_1"
  ))

use_intention_scores <- psych::scoreItems(use_intention_keys, use_intention_items, min = 1, max = 6)  

data <- data  %>% bind_cols(use_intention_scores$scores %>% as_tibble())
use_intention_scores$scores %>%  psych::describe(fast = TRUE, ranges = FALSE) %>% kable(caption = "Average use intention score", digits = 2,  row.names = FALSE) %>%  kable_material()

```

The reliability for the *use intention of AI* is `r round(use_intention_scores$alpha, 2)`.

## Evaluation of applications


```{r echo=FALSE}
#| warning: false

library(ggrepel)
data$ID <- seq.int(nrow(data))

data %>% 
  select(ID, prognose_bewertung_number_1_1:prognose_bewertung_number_1_11, prognose_bewertung_number_2_1:prognose_bewertung_number_2_11) %>% 
  pivot_longer(cols = c(prognose_bewertung_number_1_1:prognose_bewertung_number_1_11, prognose_bewertung_number_2_1:prognose_bewertung_number_2_11),names_to=c("dimension", "question"), names_pattern = "prognose_(.*)_(.*)") %>%dplyr::mutate(value = scales::rescale(value, c(-1,1))) %>% pivot_wider(names_from = dimension, values_from = value) %>% rename(expectancy=bewertung_number_1, evaluation=bewertung_number_2) %>% 
  group_by(question) %>% 
  dplyr::summarize(
    mean_expectancy = mean(expectancy, na.rm=TRUE),
    mean_evaluation = mean(evaluation, na.rm=TRUE),
    N=n()
    ) %>% 
    mutate(category= factor(question, levels = c(1:11), labels = c(
                                  "Medicine",
                                  "Consulting",
                                  "Research",
                                  "Art & Music",
                                  "Industry",
                                  "Smart Home / Assisted Living",
                                  "Security (e.g. hate speech, riot control)",
                                  "Mobility",
                                  "Military application (e.g, warfare)",
                                  "Law enforcement",
                                  "Marketing and online trade "
                                  ))) -> data_criticality_matrix
```



```{r echo=FALSE}
data_criticality_matrix %>% 
  ggplot(aes(x=mean_expectancy, y=mean_evaluation, label=category))+
  geom_point(colour="#333333") +
  geom_vline(xintercept = 0, size=.25) +
  geom_hline(yintercept = 0, size=.25) +
  geom_abline(slope = +1, colour="gray", linetype = "dotted") +
  annotate("text", hjust = 0, x = -0.9, y = -1, color="#ed6976", label = "Not likely & not valued", size=4) +
  annotate("text", hjust = 0, x = -0.9, y = +1, color="gray48", label = "Not likely & valued", size=4) +
  annotate("text", hjust = 1, x = +0.9, y = -1, color="gray48", label = "Likely & not valued", size=4) +
  annotate("text", hjust = 1, x = +0.9, y = +1, color="#50b796", label = "Likely & valued", size=4) +
  theme_dissertation() +
  geom_smooth(method = "lm", color="#f1c869", fill="#f1c869") +
  geom_text_repel(
    #ylim = c(-Inf, Inf),
    #xlim = c(-Inf, Inf),
    #max.overlaps = Inf,
    segment.color = "gray",	
    size = 5,
    min.segment.length = 0,
    box.padding = .3 
    ) +
  labs( title = "Likelyhood of occurence and valence \n of AI technologies in different domains and applications",
        #       subtitle = "sub",
        caption = "n = 137",
        x = "Estimated likelihood of occurrence", # (not likely at all - very likely)
        y = "Individual evaluation") + # (negativ - positive)  
  scale_x_continuous(labels = scales::percent_format(), limits=c( -1, +1)) + 
  scale_y_continuous(labels = scales::percent_format(), limits=c( -1, +1))

ggsave('./exports/criticality-matrix.png', width = 18, height = 10, units = "cm", scale = 1.5)
ggsave('./exports/criticality-matrix.svg', width = 18, height = 10, units = "cm", scale = 1.5)


  
```

## Correlation analysis

```{r}
library(apaTables)
data %>% select(kusiv_scores, risikobereitschaft_1, sensitivity_scores, bdws_scores, ati_scores, general_attitude_scores, use_intention_scores, trust_ai_scores) -> cortable
apa.cor.table(cortable, show.sig.stars = TRUE, filename = "exports/cortable.tex")
```

