---
title: 'Introduction: 2 schools from the NELS data'
author: "Carolyn J. Anderson"
date: "12/27/2022"
output: 
   html_document:
     toc: yes
---


# Data set up
 
 The data include all 1003 schools but we'll only look at 2 of them.  The data are in csv format and I will be lazy and just delete the missing values.  
 
## Read in data and look
 ```{r}
setwd("D:/Dropbox/edps587/lectures/1 introduction")

nels <- read.csv("nels_data.csv",header=TRUE,sep=",")
nels <- na.omit(nels)
head(nels)
```

## Select 2 schools

We'll pull out data for schools 24725 and 62821
```{r twoschools}
nels1 <- nels[ which(nels$sch_id==24725 | nels$sch_id==62821), ]
```

# Graph data

## Basic
We'll start with a plane scatter plot with a linear regression overlayed
```{r}
plot(nels1$homework,nels1$math, type="p", pch=19,
     main=expression(paste("NELS Data (sub-set) ")),
	 xlab="Time Spent Doing Homework",
	 ylab="Math Scores",
	 xlim=c(0,7),
	 ylim=c(20,80)
	 )
abline(lm(nels1$math ~ nels1$homework),col="blue",lwd=2)
summary(lm1<- lm(nels1$math ~ nels1$homework))
text(19,47.5, "math = 47.97 + 3.49*homework",cex=1.25)
```

Does linear regression look OK?  What do you notice about the data?

## Graph with Jitter
Note that some students have the same values.  To get a better idea of how much 
data there are, we'll "jitter" the points a bit


```{r jitter}
plot(jitter(nels$homework),nels$math, type="p", pch=19,
     main=expression(paste("NELS Data (sub-set) with some Horizondent Jittering")),
	 xlab="Time Spent Doing Homework",
	 ylab="Math Scores",
	 xlim=c(0,7),
	 ylim=c(20,80)
	 )
abline(lm(nels1$math ~ nels1$homework),col="blue",lwd=2)
summary(lm1<- lm(nels1$math ~ nels1$homework))
text(19,47.5, "math = 47.97 + 3.49*homework",cex=1.25)
```

## Identify the Schools

We know that we have two schools, it is insightful note this in the figure.
```{r}
nels.s1 <- nels[ which(nels$sch_id==24725), ]

nels.s2 <- nels[ which(nels$sch_id==62821), ]

# Graph to illustrate need for random intercept and slope
# -- create frame for plot, notice that type='n' for none 
par(new=FALSE)
plot(jitter(nels.s1$homework),nels.s1$math,
	type="p", pch=19,
	col="blue",
	lwd=2,
	main="NELS: Linear Regression by School",
	xlab="Time Spent Doing Homework",
	ylab="Math Scores",
	xlim=c(0,7),
	ylim=c(20,80)
	)
abline(lm(math ~ homework,data=nels.s1),col="blue")
par(new=TRUE)
plot(jitter(nels.s2$homework),nels.s2$math,type="p",
    pch=19,
	col="red",
	xlab="Time Spent Doing Homework",
	ylab="Math Scores",
	xlim=c(0,7),
	ylim=c(20,80)
)
abline(lm(math ~ homework,data=nels.s2),col="red",pch=19)
legend(4, 35, legend=c("School 62821","School 24725"), 
       col=c("red","blue"), lty=1, cex=1.1,
       box.lty=1, box.lwd=1)
```

The schools have different intercepts and slopes.  In this case, the higher intercept, the smaller slope.
