---
title: "S4 - QAP Self-reported measures"
output:
  html_document:
    theme: cerulean
---

```{r setup, include=FALSE, echo=FALSE, message=FALSE}
knitr::opts_chunk$set(
  collapse = TRUE,
  echo = FALSE, 
  message = FALSE, 
  warning = FALSE,
  comment = "#>"
)

rm(list=ls())
gc()


# CRAN libraries 
library(network)
library(sna)
library(tidyverse)

# Download and install from Github https://github.com/jmueller17/sociometrics
library(sociometrics)

# Download and install from Zenodo https://doi.org/10.5281/zenodo.3446071
library(gediismtrx)
data("gedii_sociodemo_fix")
data("gedii_rr")
data("gedii_interaction")

source("S4_utility.fun.R")


do.qap <- function(team, fun="netlm"){
  
  
  if (team == 71) {
    
    rrmatrix <- rem_covars(gedii_rr[[7]], covar_t="rr")
    soc <- rrmatrix[["m_soc"]]
    adv <- rrmatrix[["m_adv"]]
    
    soc <- soc[c(1:7),c(1:7)]
    adv <- adv[c(1:7),c(1:7)]
            
    
  } else if (team == 72){
    
    rrmatrix <- rem_covars(gedii_rr[[7]], covar_t="rr")
    soc <- rrmatrix[["m_soc"]]
    adv <- rrmatrix[["m_adv"]]
    
    soc <- soc[c(8:14),c(8:14)]
    adv <- adv[c(8:14),c(8:14)]
    
    
  }  else {
    
    rrmatrix <- rem_covars(gedii_rr[[team]], covar_t="rr")
    soc <- rrmatrix[["m_soc"]]
    adv <- rrmatrix[["m_adv"]]
  }


  
  socm <- rr_rating(soc, directed=F, to.undir="mean", as.type="matrix", impute.na="recip")
  advm <- rr_rating(adv, directed=F, to.undir="sum", as.type="matrix", impute.na="recip")
  
  
  rdim <- dim(soc)[1]
  

    
  rsl <- qaptest(list(advm, socm), gcor, g1=1, g2=2, reps=1000, diag=FALSE, mode="digraph")
  rsl <- summary(rsl)
    
  

  rsl
}

```


### Dyad based correlation 

```{r}

teams <- c(1:6,71,72,8)


friends <- bind_rows(lapply(teams, comb.rr, "m_soc", directed=T, to.undir="weight", impute.na="recip"))
advice <-  bind_rows(lapply(teams, comb.rr, "m_adv", directed=T, to.undir="weight", impute.na="recip"))

friends <- dplyr::rename(friends, soc_score=weight)
advice <- dplyr::rename(advice, adv_score=weight)

friends %<>% 
  left_join(advice, by="edge") %>% 
  select(edge, soc_score, adv_score)

friends$soc_score <- as.numeric(friends$soc_score)
friends$adv_score <- as.numeric(friends$adv_score)

cor.test(friends$soc_score, friends$adv_score, method = "spearman")

```

<p>&nbsp;</p>
<p>&nbsp;</p>


### Network based (QAP) 


#### All teams 
```{r}

set.seed(6778)

teams <- c(1:6, 71, 72, 8)

df <- data.frame()

for (i in teams){
  rs <- do.qap(i, "qaptest")
  df <- bind_rows(df, data.frame(cor=round(rs$testval,3), pval=rs$pgreq, pleeq=rs$pleeq, team=i))
}


df
```


<p>&nbsp;</p>
<p>&nbsp;</p>
# Package- and Session Info 
```{r}
sessionInfo()
```

