library(tidyverse)
library(magrittr)
library(viridis)

# Added 07.02.2020 for working out Raincloud plots ... see towards the end.
library(grid)
library(cowplot)
source("R_Rainclouds.R") # This is the source with functions for raincloud plotting ... see below.

#Create a variable called behavdata and read into it, the data from the file allresfilter_3words_split.out.

behavdata <- read.table("allres_filtersplit.out")  #Input

### Although GD (Gender) is there in the input file, this script does not enter it as a factor.
### See Behavdata-VagreeAGR-Gender.R for the analysis entering GD as a factor.

#Give names to each field in the data just read.
names(behavdata) <- c("SNo", "Block", "Trial", "Item", "Condition", "Sentence", "ST", "CT", "GD", "RT", "Acceptability", "Answer", "Type")

#The new versions of R do not take a purely numeric input column as a factor,
#unless it is EXPLICITLY DECLARED to be taken as a factor.  Since the 'Item' column in our input files
#is a purely numeric one, this has to be explicity declared to be taken as a factor, 
#as follows: - (Thanks to Petra for pointing this out).
behavdata$Item <- as.factor(behavdata$Item) 


# Example row from allres_filtersplit.out
# VA01 1   1   20    SAF   20SAF     S   AGR  1.192 2               2         AGRTarget
# SNo  Bl  Tr  Item  Cond  Sentence  ST  CT RT    Acceptability   Accuracy  Type => AGReement Target (i.e., not Verb-initial / Resumpro / Filler).

#behavdata_Correct <- behavdata[behavdata$F1=="2",]

b_t   <- behavdata[behavdata$Type=="AGRTarget",]  # Only AGRTagert sentences.
b_tc  <- b_t[b_t$Answer=="2",]    # Correctly answered Dative targets;


#Indicate R the file name under which the results are to be saved.
#sink("BehavdataAGRStats.txt")  #Output

print("Total")
## [1] "Total"
print(dim(behavdata))
## [1] 20342    13
print("Correctly answered AGR Targets")
## [1] "Correctly answered AGR Targets"
print(dim(b_tc))
## [1] 9263   13
# Raincloud plot
# https://github.com/RainCloudPlots/RainCloudPlots
# Through Ina's 2020 Icelandic paper

library(grid) # To be able to use unit() below


#Acceptability judgements
Acpt_by_Participant <- b_tc %>%
  dplyr::filter(ST == "S" | ST == "P") %>%
  mutate(ST = fct_relevel(ST, c("S", "P"))) %>% 
  # Since the input data has more levels for CT/ST, the levels S and P (or P and S) do not correspond to 1 and 2; 
  # Relevel the factors so they are in the place we want them to be. Similarly factor relevel CT.
  mutate(CT = fct_relevel(CT, c("ACP", "GEN", "NUM", "PER"))) %>%