---
title: "Homework Chapter 10"
author: "Dr. Paul Pearson"
date: "2024-11-01"
output: html_document
---

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

library(ggplot2) 
# ggsave(ggplot_object) can save svg files without xml annotations

library(BrailleR) 
# VI(ggplot_object) for annotations for in text graph annotations
# MakeAccessibleSVG(ggplot_object) to save accessible standalone html (=svg + xml annotations)

library(tactileR) 
# Use braille in graphs for embossed printing
# brl_begin(file='tactile_histogram_SWL.pdf', pt=14, paper='special', font='SWL')
# base or lattice plot code here
# brl_end()

library(infer)
#library(tibble)

library(tidyr) # for reshaping data, etc.

library(car) # for fancy scatterplots

set.seed(1)
options(digits = 4)
```



# Define helper functions

```{r}
make_graphs <-  function(df, explanatory, response, title_string, xlab_string, ylab_string, filename) {

  formula_string <- paste(substitute(response), "~", substitute(explanatory))
  # winner: https://win-vector.com/2019/07/06/programming-over-lm-in-r/
  # https://stackoverflow.com/questions/27261232/passing-argument-to-lm-in-r-within-function
  model <- eval(bquote(   lm( as.formula(formula_string), data = df)   ))
  
  
  # ggplot scatterplot without line
  sp <- ggplot(df, aes( x = {{ explanatory }}, y = {{ response }} )) +
    geom_point(size = 4) + 
    ggtitle( title_string ) +
    xlab( xlab_string ) + 
    ylab( ylab_string ) +
    theme_bw(base_size = 18)
  
  print(sp) # generates both graph and VI(ts) automatically 
  
  # ggplot scatterplot with line
  sp <- sp + geom_smooth(method='lm', se=FALSE, size=2, color = "black")

  print(sp) # generates both graph and VI(ts) automatically
  
  MakeAccessibleSVG.ggplot(sp, file = paste0("reader-", filename))

  # tactile scatterplot with no line  
  brl_begin(paste0( 'tactile-', filename, '-scatterplot.pdf'), 
          pt=12, paper='special', font='SWL') #, font='BRL' or 'SWL')
    # to get the variable values, use data[[substitute(varname)]] instead of data$varname
    plot(df[[substitute(explanatory)]],
         df[[substitute(response)]],
         main = title_string,
         xlab = xlab_string,
         ylab = ylab_string
         )
  brl_end()
  

  # tactile scatterplot with line  
  brl_begin(paste0( 'tactile-', filename, '-scatterplot-and-line.pdf'), 
          pt=12, paper='special', font='SWL') #, font='BRL' or 'SWL')
    # to get the variable values, use data[[substitute(varname)]] instead of data$varname
    plot(df[[substitute(explanatory)]],
         df[[substitute(response)]],
         main = title_string,
         xlab = xlab_string,
         ylab = ylab_string
         )
    abline( model, col = "black", lwd = 3 )
  brl_end()
  

  # tactile scatterplot with line and ellipses and boxplots 
  brl_begin(paste0( 'tactile-', filename, '-scatterplot-and-line-and-ellipses-and-boxplots.pdf'), 
         pt=12, paper='special', font='SWL') #, font='BRL' or 'SWL')
  scatterplot( as.formula(formula_string), data = df,
      main = title_string,
      xlab = xlab_string,
      ylab = ylab_string,
             pch = 16, cex = 2, col = "black",
             smooth = FALSE, grid = FALSE, frame = TRUE,
             ellipse = list(levels=c(.25, .75), robust=TRUE, fill=FALSE, fill.alpha=0, lwd = 3) )
  brl_end()


}

```



# HW 10.1.1

```{r}
hike <- read.table(text=
"distance_mi	time_min
0.6097186336	20.32467532
0.9050679996	30.35714286
1.013197929	40.98678108
1.510114442	60.29637592
1.509591285	45.40584416
1.80488472	60.28733766
2.107534689	60.43194981
2.211915266	90.18752081
2.560801906	89.99002023
2.512130856	60.29637592
2.812892859	89.99458874
3.009500625	89.99458874
3.208011736	90.12263075
3.453380132	90.16378711
3.803841346	119.8133117
4.009197009	149.9107143
4.010004961	120.1477273
4.557401918	120.1099707
4.61306372	149.9107143
5.013472219	149.9107143
5.513155229	180.0081169
5.567220817	149.9107143
5.800632131	180.0081169
6.01152509	180.0081169
7.010177463	179.882711
7.41944808	419.1152597
9.516062599	299.5616883", header=TRUE, check.names=FALSE)

#print(hike, row.names=FALSE)
```


```{r, fig.cap="This scatter plot has title ‘Hiking distance versus time’ with x-axis ‘distance (miles)’ that has values from 0 to 10, and y-axis ‘time (minutes)’ with values from 0 to 400.  There are 27 big solid circle points. The points are concentrated tightly around a straight path (except for one outlier) that is increasing at a constant rate of about 30 minutes for every mile."}
make_graphs( df = hike, 
             explanatory = distance_mi, 
             response = time_min, 
             title = "HW 10.1 #1 hiking distance vs time", 
             xlab_string = "distance (miles)", 
             ylab_string = "time (minutes)",
             filename = "HW_10.1.1"
             )
```



```{r, echo=FALSE, fig.cap="This scatter plot has title ‘Hiking distance versus time’ with x-axis ‘distance (miles)’ that has values from 0 to 10, and y-axis ‘time (minutes)’ with values from 0 to 400.  There are 27 big solid circle points. The points are concentrated tightly around a straight path (except for one outlier) that is increasing at a constant rate of about 30 minutes for every mile."}
# time series plot
sp <- ggplot(hike, aes(distance_mi, time_min)) +
  geom_point(size = 4) + 
  ggtitle("HW 10.1 #1: Hiking distance versus time") +
  xlab("Distance (miles)") + 
  ylab("Time (minutes)") +
  theme_bw(base_size = 18)
sp # generates both graph and VI(ts) automatically

lm(time_min ~ distance_mi, hike)
```

```{r, echo=FALSE, fig.cap="This scatter plot has title ‘Hiking distance versus time’ with x-axis ‘distance (miles)’ that has values from 0 to 10, and y-axis ‘time (minutes)’ with values from 0 to 400.  There are 27 big solid circle points. The points are concentrated tightly around a straight path (except for one outlier) that is increasing at a constant rate of about 30 minutes for every mile. The graph also has a line of best fit."}
# time series plot
sp <- ggplot(hike, aes(distance_mi, time_min)) +
  geom_point(size = 4) + 
  ggtitle("HW 10.1 #1: Hiking distance versus time") +
  xlab("Distance (miles)") + 
  ylab("Time (minutes)") +
  theme_bw(base_size = 18) +
  geom_smooth(method='lm',
            se=FALSE, 
            size=2,
            color = "black")

sp # generates both graph and VI(ts) automatically

lm(time_min ~ distance_mi, hike)
```



```{r, include=FALSE, fig.cap="This scatter plot has title ‘Hiking distance versus time’ with x-axis ‘distance (miles)’ that has values from 0 to 10, and y-axis ‘time (minutes)’ with values from 0 to 400.  There are 27 big solid circle points. The points are concentrated tightly around a straight path (except for one outlier) that is increasing at a constant rate of about 30 minutes for every mile."}
#MakeAccessibleSVG.ggplot(sp, file = "reader-HW_10_1_1")
```



```{r, include=FALSE}

# brl_begin('tactile-HW_10_1_1_scatterplot.pdf', 
#           pt=12, paper='special', font='SWL') #, font='BRL' or 'SWL')
# plot(hike$distance_mi,
#      hike$time_min, 
#      main = "HW 10.1.1 hiking distance vs time",
#      xlab = "Distance (miles)",
#      ylab = "Time (minutes)"#,
#      #ylim = c(0,0.5)
#      #type = "o", # both points p and lines l
#      #lwd = 3, # line width = 3
#      #pch = 16,
#      )
# brl_end()

```

```{r, include=FALSE}

# brl_begin('tactile-HW_10_1_1_scatterplot_and_line.pdf', 
#           pt=12, paper='special', font='SWL') #, font='BRL' or 'SWL')
# plot(hike$distance_mi,
#      hike$time_min, 
#      main = "HW 10.1.1 hiking distance vs time",
#      xlab = "Distance (miles)",
#      ylab = "Time (minutes)"#,
#      #ylim = c(0,0.5)
#      #type = "o", # both points p and lines l
#      #lwd = 3, # line width = 3
#      #pch = 16,
#      )
# abline(lm(time_min ~ distance_mi, data = hike), col = "black", lwd = 3)
# brl_end()

```



```{r, echo=FALSE}
#plot(hike$distance_mi, hike$time_min)
#ScatterPlot(hike, x=hike$distance_mi, y=hike$time_min)
```







# HW 10.1.3 about glycemic loads and mean rating

```{r}
foods <- read.table(text=
"MeanRating	GlycemicLoad
4.01	22
3.73	14
3.73	12
3.71	7
3.68	14
3.6	21
3.51	17
3.29	16
3.26	24
3.22	0
3.03	0
2.97	7
2.73	15
2.64	26
2.56	22
2.57	22
2.54	0
2.5	29
2.47	3
2.18	0
2.16	0
2.13	15
2.07	11
1.94	0
1.93	10
1.88	1
1.87	8
1.84	0
1.77	12
1.74	0
1.74	20
1.66	4
1.63	7
1.6	2
1.53	0", header=TRUE, check.names=FALSE)
```


```{r, echo=FALSE, fig.cap="This scatter plot has title ‘Glycemic load versus mean rating’ with x-axis ‘glycemic load’ that has values from 0 to 30, and y-axis ‘mean rating’ with values from 1.5 to 4.  There are 35 big solid circle points. The points are quite spread out horizontally and vertically but they do show a general slight increase in mean rating as glycemic load increases."}
sp <- ggplot(foods, aes(GlycemicLoad, MeanRating)) +
  geom_point(size = 4) + 
  ggtitle("HW 10.1 #3: glycemic load vs mean rating") +
  xlab("glycemic load") + 
  ylab("mean rating") +
  theme_bw(base_size = 18)

sp
```

```{r, echo=FALSE, fig.cap="This scatter plot has title ‘Glycemic load versus mean rating’ with x-axis ‘glycemic load’ that has values from 0 to 30, and y-axis ‘mean rating’ with values from 1.5 to 4.  There are 35 big solid circle points. The points are quite spread out horizontally and vertically but they do show a general slight increase in mean rating as glycemic load increases."}
sp <- ggplot(foods, aes(GlycemicLoad, MeanRating)) +
  geom_point(size = 4) + 
  ggtitle("HW 10.1 #3: glycemic load vs mean rating") +
  xlab("glycemic load") + 
  ylab("mean rating") +
  theme_bw(base_size = 18) +
  geom_smooth(data =  foods, 
            method='lm',
            se=FALSE, 
            size=2,
            color = "black")

sp # generates both graph and VI(ts) automatically

lm(MeanRating ~ GlycemicLoad, foods)
```

```{r, echo=FALSE, fig.cap="This scatter plot has title ‘Glycemic load versus mean rating’ with x-axis ‘glycemic load’ that has values from 0 to 30, and y-axis ‘mean rating’ with values from 1.5 to 4.  There are 35 big solid circle points. The points are quite spread out horizontally and vertically but they do show a general slight increase in mean rating as glycemic load increases."}
MakeAccessibleSVG.ggplot(sp, file = "reader-HW_10_1_3")
```


```{r, include=FALSE}
brl_begin('tactile-HW_10_1_3_scatterplot.pdf', 
          pt=12, paper='special', font='SWL') #, font='BRL' or 'SWL')
plot(foods$GlycemicLoad,
     foods$MeanRating, 
     main = "HW 10.1.3 glycemic load vs mean rating",
     xlab = "glycemic load",
     ylab = "mean rating"
     )
brl_end()
```

```{r, include=FALSE}
brl_begin('tactile-HW_10_1_3_scatterplot_and_line.pdf', 
          pt=12, paper='special', font='SWL') #, font='BRL' or 'SWL')
plot(foods$GlycemicLoad,
     foods$MeanRating, 
     main = "HW 10.1.3 glycemic load vs mean rating",
     xlab = "glycemic load",
     ylab = "mean rating"
     )
abline(lm(MeanRating ~ GlycemicLoad, data = foods), col = "black", lwd = 3)
brl_end()
```


```{r}
brl_begin('tactile-HW_10_1_3_scatterplot_and_line_and_ellipse.pdf', 
          pt=12, paper='special', font='SWL') #, font='BRL' or 'SWL')
scatterplot(MeanRating ~ GlycemicLoad, data = foods,
     main = "HW 10.1.3 glycemic load vs mean rating",
     xlab = "glycemic load",
     ylab = "mean rating",
            pch = 16, cex = 2, col = "black",
            smooth = FALSE, grid = FALSE, frame = TRUE,
            ellipse = list(levels=c(.25, .75), robust=TRUE, fill=FALSE, fill.alpha=0, lwd = 3) )
brl_end()
```






# HW 10.1.4 on housing prices and location


```{r}
houses <- read.table(text=
"sqft	price	location
900.4245641	121.4827342	notlakefront
1332.911007	202.2002959	notlakefront
1664.055598	182.3960118	notlakefront
2236.790998	241.6676939	notlakefront
2272.71276	213.7819329	notlakefront
2407.247765	328.0687403	notlakefront
3165.875711	314.1584852	notlakefront
1597.275542	412.0484081	lakefront
1736.981082	532.1023415	lakefront
1904.070236	497.9171293	lakefront
2695.003193	643.0897783	lakefront
3258.721474	754.0413121	lakefront
3351.031211	901.4073519	lakefront", header=TRUE, check.names=FALSE)

notlakefront <- subset(houses, location == "notlakefront")
lakefront <- subset(houses, location == "lakefront")


print(houses, row.names=FALSE)
```

## House prices

```{r, echo=FALSE, fig.cap="This scatter plot has title ‘Housing price versus square footage of home’ with x-axis ‘square footage’ that has values from 500 to 3500, and y-axis ‘price / 1000’ with values from 100 to 900 (in units thousands of dollars).  There are 12 big solid circle points. The points are spread out but do show a general increase in price as square footage increases."}
# time series plot
sp <- ggplot(houses, aes(sqft, price)) +
  geom_point(size = 4) + 
  ggtitle("HW 10.1 #4: House price versus sq ft") +
  xlab("sq ft") + 
  ylab("Price/1000") +
  theme_bw(base_size = 18) +
  geom_smooth(data =  houses, 
            method='lm',
            se=FALSE, 
            size=2,
            color = "black")

sp # generates both graph and VI(ts) automatically

lm(price ~ sqft, houses)
```

```{r, include=FALSE, fig.cap="This scatter plot has title ‘Hiking distance versus time’ with x-axis ‘distance (miles)’ that has values from 0 to 10, and y-axis ‘time (minutes)’ with values from 0 to 400.  There are 27 big solid circle points. The points are concentrated tightly around a straight path (except for one outlier) that is increasing at a constant rate of about 30 minutes for every mile."}
MakeAccessibleSVG.ggplot(sp, file = "reader-HW_10_1_4")
```

```{r, include=FALSE}
brl_begin('tactile-HW_10_1_4.pdf', 
          pt=12, paper='special', font='SWL') #, font='BRL' or 'SWL')
plot(houses$sqft,
     houses$price, 
     main = "HW 10.1.4 house price vs sq ft",
     xlab = "sq ft",
     ylab = "Price/1000"#,
     #ylim = c(0,0.5)
     #type = "o", # both points p and lines l
     #lwd = 3, # line width = 3
     #pch = 16,
     )
brl_end()
```


## Lakefront house prices

```{r, echo=FALSE, fig.cap="This scatter plot has title ‘Housing price versus square footage of home’ with x-axis ‘square footage’ that has values from 500 to 3500, and y-axis ‘price / 1000’ with values from 100 to 900 (in units thousands of dollars).  There are 12 big solid circle points. The points are spread out but do show a general increase in price as square footage increases."}
# time series plot
sp <- ggplot(houses, aes(sqft, price)) +
  geom_point(size = 4) + 
  ggtitle("HW 10.1 #4: House price versus sq ft") +
  xlab("sq ft") + 
  ylab("Price/1000") +
  theme_bw(base_size = 18) +
  # https://stackoverflow.com/questions/42132442/ggplot-adding-regression-line-of-different-subsets
  geom_smooth(data =  subset(houses, location == "lakefront"), 
              method='lm',
              se=FALSE, 
              size=2,
            color = "black") +
  geom_smooth(data =  subset(houses, location == "notlakefront"), 
              method='lm',
              se=FALSE, 
              size=2,
            color = "black")


sp # generates both graph and VI(ts) automatically

lm(price ~ sqft, houses)
```







