```{r setup, include=FALSE}
rm(list=ls())

knitr::opts_chunk$set(echo = TRUE)
```

This week we will learn how to compute and analyze correlations

Let's look at the phd data from async. First, import the data.
```{r}
phd_data <- read.table("week11_phd.txt", header=TRUE, sep="\t")
```
LOOK at your data after you import it! How many vars? How many observations? Note variable names, etc.

Now let's make make a scatterplot (IV on x-axis; DV on y-axis)
```{r}
plot(phd_data$Time, phd_data$Pubs, 
     main="Scatterplot of Time & Publications", 
     xlab="Time Since PhD Grad (in years)", 
     ylab="Publications", pch=15)
```

We can use R to compute the Pearson Correlation and obtain other values for the hypothesis test
```{r}
cor.test(phd_data$Time, phd_data$Pubs, method="pearson")
```

Calculate effect size (R^2)
```{r}
0.6566546^2
```

Now, let's look the example from asyc for the spearman correlation.
```{r}
english_data <- read.table("week11_english.txt", header=TRUE, sep="\t")

cor.test(english_data$Words, english_data$Grade, method="spearman")
```

Point-Biserial Correlation (note that this code is the same as Pearson's, but the data setup differs)
```{r}
byod_data <- read.table("week11_byod.txt", header=TRUE, sep="\t")

cor.test(byod_data$Byod, byod_data$Grade) #pt-biserial

#calculate effect size - R^2
0.378822^2
```

Phi Correlation (note that this code is the same as Pearson's, but the data setup differs)
```{r}
grad_data <- read.table("week11_graduate.txt", header=TRUE, sep="\t")

table(grad_data)

cor.test(grad_data$Business, grad_data$Doctorate) #phi 

#calculate effect size
(-0.2228072)^2
```

Ben's code for using R to find the critical value for Pearson correlation. Function = critical.r
```{r}
critical.r <- function(n, alpha = .05) {
  df <- n - 2
  critical.t <- qt(alpha/2, df, lower.tail = F )
  critical.r <- sqrt((critical.t^2)/((critical.t^2) + df ) )
  return( critical.r )
}

#enter n-size in function
critical.r(18)
```

Plotting a prettier scatterplot using ggplot (note - we will be using ggplot for EVERY plot next term... go ahead and get your feet wet here).
```{r}
library(ggplot2) #you could load tidyverse here instead, because that contains GGPLOT2 (either way works!)

# Basic scatter plot
ggplot(phd_data, aes(x=Time, y=Pubs))+ 
  geom_point(size=2, shape=16, color="blue")+
  labs(x="Time Since PhD Grad (in years)", y="Publications")+
  theme_classic() #this removes the gray/grid background
```


