# Exercise 06 from "dplyr, or a dance with data"
#
# Author: Danielle Navarro (d.navarro@unsw.edu.au)
# Date: 11 March 2020


# preliminaries -----------------------------------------------------------

# load packages
library(tidyverse)
## ── Attaching core tidyverse packages ──────────────────────── tidyverse 2.0.0 ──
## ✔ dplyr     1.1.4     ✔ readr     2.1.5
## ✔ forcats   1.0.0     ✔ stringr   1.5.1
## ✔ ggplot2   3.5.1     ✔ tibble    3.2.1
## ✔ lubridate 1.9.3     ✔ tidyr     1.3.1
## ✔ purrr     1.0.2     
## ── Conflicts ────────────────────────────────────────── tidyverse_conflicts() ──
## ✖ dplyr::filter() masks stats::filter()
## ✖ dplyr::lag()    masks stats::lag()
## ℹ Use the conflicted package (<http://conflicted.r-lib.org/>) to force all conflicts to become errors
# import data
swow <- "data_swow.csv.zip" %>%
  read_tsv() %>%           # read the data from file
  mutate(id = 1:n()) %>%   # add the "id" column
  rename(
    n_response = R1,       # nicer name for the response count
    n_total = N,           # nicer name for the total cue presentations
    strength = R1.Strength # nicer name for the estimated response strength  
  )
## Multiple files in zip: reading 'swow.csv'
## Rows: 483636 Columns: 5
## ── Column specification ────────────────────────────────────────────────────────
## Delimiter: "\t"
## chr (2): cue, response
## dbl (3): R1, N, R1.Strength
## 
## ℹ Use `spec()` to retrieve the full column specification for this data.
## ℹ Specify the column types or set `show_col_types = FALSE` to quiet this message.
# words associated with "man" and "woman" ---------------------------------

woman_fwd <- swow %>%
  filter(cue == "woman", n_response > 1) %>%
  select(cue, response, strength, id) %>%
  mutate(
    rank = rank(-strength),  # rank the data by strength
    type = "forward",        # this is forward associate (i.e., it's woman_FWD)
    word = "woman",          # the word is "woman" (i.e., it's WOMAN_fwd)
    associate = response     # for forward associations, the RESPONSE is the asociate
  )

woman_bck <- swow %>%
  filter(response == "woman", n_response > 1)  %>%
  arrange(desc(strength)) %>%
  select(cue, response, strength, id) %>%
  mutate(
    rank = rank(-strength),  # rank the data by strength
    type = "backward",       # this is backward associate (i.e., it's woman_BCK)
    word = "woman",          # the word is "woman" (i.e., it's WOMAN_bck)
    associate = cue          # for backward associations, the CUE is the associate
  )

man_fwd <- swow %>%
  filter(cue == "man", n_response > 1)  %>%
  select(-n_response, -n_total)   %>%
  mutate(
    rank = rank(-strength),  # rank of the association
    type = "forward",        # direction of the association
    word = "man",            # word being "associated to"
    associate = response     # word that is the "associate of"
  )

man_bck <- swow %>%
  filter(response == "man", n_response > 1) %>%
  arrange(desc(strength)) %>%
  select(-starts_with("n_")) %>% # ... remove variables starting with "n_"
  mutate(
    rank = rank(-strength),  # rank of the association
    type = "backward",       # direction of the association
    word = "man",            # word being "associated to"
    associate = cue          # word that is the "associate of"
  )



# combine the data sets ---------------------------------------------------

gender <- bind_rows(woman_fwd, woman_bck, 
                    man_fwd, man_bck) %>% # binding rows of data columns matched by name 
  select(id:associate) %>% # selecting from id to associate 
  filter(associate != "man", associate != "woman") # get rid of associates with man or woman in them 



# create and plot gender_fwd ----------------------------------------------

gender_fwd <- gender %>% 
  filter(
    type == "forward"
  ) %>% # selecting for only forward 
  pivot_wider(
    id_cols = associate, # first column = associate 
    names_from = word, # names of word column used to organise columns
    values_from = rank # values taken from rank column 
  ) %>%
  mutate(
    woman = replace_na(1/woman, 0), # make new woman value 1/ old woman value 
    man = replace_na(1/man, 0), # replace values of NA with 0
    diff = woman - man # caluculate the difference between new woman and man scores 
  )  %>%  
  arrange(diff) # arrange values by smallest to largest difference


picture_fwd <- ggplot(
  data = gender_fwd, # taking data from gender_fwd
  mapping = aes(
    x = associate %>% reorder(diff), # associate is reordered by difference
    y = diff 
  )) + 
  geom_col() + # create bar chart with height of data representing data 
  coord_flip() # flip the coordinates

#plot(picture_fwd)



# create and plot gender_bck ----------------------------------------------


# YOUR TURN...
#
# 1. The previous section contains all the code that I used in the slides
#    to draw the plot of gender_fwd. Source this script to check that it 
#    works.
#
# 2. The code in the previous section has one very bad flaw... there are
#    no comments. Try to add comments to this code so that when YOU have
#    to read it again in a few weeks (months) times, you can work out 
#    what it is doing
#
# 3. In THIS section, try to modify the code from the previous section
#    so that it creates and plots of the "gender_bck" variable. Your result
#    should look the same as the figure shown in the slide


gender_bck <- gender %>%
  filter(type == "backward") %>% # use only backward values 
  pivot_wider(
    id_cols = associate, # identified by associate
    names_from = word, # names from woman or man 
    values_from = rank # values from rank 
  ) %>% 
  mutate(
    woman = (1/woman) %>% replace_na(0), # new woman or man value and replace NA with 0 
    man = (1/man) %>% replace_na(0),
    diff = woman - man # difference between new woman and man values 
  ) %>%
  arrange(diff) # organised by difference from smallest to largest
  
picture_bck <- ggplot(
  data = gender_bck, # taking data from gender_bck
  mapping = aes(
    x = associate %>% reorder(diff), # associate is reordered by difference
    y = diff 
  )) + 
  geom_col() + # create bar chart with height of data representing data 
  coord_flip() # flip the coordinates

plot(picture_bck)