library(flextable)

library(magrittr)
library(corrr)
library(tidyverse)

data <- readRDS(file.path("..", "data", "hq-data.rds"))

formatAsTable <- readRDS("format.rds")

To build a correlation matrix of the variables, I first need to score the Likert scales for affective trust (aff.s), cognitive trust (cog.s), and liking (lik.s).

data <- data %>%
  mutate(across(c("cog4.int", "lik3.int", "lik4.int"),
                ~ 6 - .,
                .names = "{.col}.r"))

data <- data %>%
  rowwise(id) %>%
  mutate(aff.s = mean(c(aff1.int, aff2.int,
                        aff3.int, aff4.int)),
         cog.s = mean(c(cog1.int, cog2.int,
                        cog3.int, cog4.int.r)),
         lik.s = mean(c(lik1.int, lik2.int,
                        lik3.int.r, lik4.int.r))) %>%
  ungroup

Now I’ll give the correlation matrix the old college try.

cor.tbl <- data %>%
  select(c(disclose, interdep, aff.s, cog.s, lik.s)) %>%
  correlate %>%
  shave
  
cor.tbl %>%
  formatAsTable

In APA style, two columns are added to the left-hand side of the matrix for means and standard deviations.

cor.tbl <- cor.tbl %>%
  rowwise %>%
  mutate(Mean = mean(data[[term]]),
         "s.d." = sd(data[[term]]),
         .before = disclose) %>%
  ungroup

cor.tbl %>%
  formatAsTable

Finally, I need to rename the terms and format the values. APA style uses the natural numbers as headers.

varnames <- c("Disclosure", "Interdependence",
              "Affective trust", "Cognitive trust",
              "Liking") %>%
  map2_chr(as.character(1:5), ~ paste0(.y, ". ", .x))

cor.tbl %>%
  rename_with(~ as.character(1:4), disclose:cog.s) %>%
  select(-term & -lik.s) %>%
  add_column(Variable = varnames, .before = "Mean") %>%
  mutate(across(as.character(1:4),
                ~ str_remove(str_remove(., "0(?=.)"),
                             "(?<=.\\d{2})\\d*"))) %>%
  formatAsTable %>%
  align(j = as.character(1:4), align = "right", part = "all")

Save data:

saveData <- function(data, name) {
  base <- file.path("..", "data", name)
  saveRDS(data, paste0(base, ".rds"))
  write_csv(data, paste0(base, ".csv"))
}

saveRDS(saveData, "save.rds")
data %>%
  saveData("scored-data")

Output document:

options(knitr.duplicate.label = "allow")
rmarkdown::render("correlation.Rmd",
                  output_dir = file.path("..", "github", "thesis"))