### **Instructions**

Homework is optional, but we recommend it so you can get the most out of this course.

```{r initiatePackages, message=FALSE}
## you can add more, or change...these are suggestions
library(tidyverse)
library(readr)
library(dplyr)
library(ggplot2)
library(tidyr)
```


### **Problem Set**

1\. Create the following two objects.

(a) Make an object "bday". Assign it your birthday in day-month format (1-Jan). 
(b) Make another object "name". Assign it your name. Make sure to use quotation marks for anything with text!

```{r 1response}
bday <- "19-Feb"
name <- "Bruce Wayne"
```


2\. Make an object "me" that is "bday" and "name" combined.

```{r 2response}
me <- c(bday, name)
```


3\. Determine the data class for "me".

```{r 3response}
class(me)
# The class for "me" is "character"
```


4\. If I want to do `me / 2` I get the following error: `Error in me/2 : non-numeric argument to binary operator`. Why? Write your answer as a comment inside the R chunk below.

```{r response}
# R cannot perform math functions on character data classes (types).
```


**The following questions involve an outside dataset.** 

We will be working with a dataset from the "Kaggle" website, which hosts competitions for prediction and machine learning. This particular dataset contains information about temperature measures from the Rover Environmental Monitoring Station (REMS) on Mars. These data are collected by Spain and Finland. More details on this dataset are here: https://www.kaggle.com/datasets/deepcontractor/mars-rover-environmental-monitoring-station/data.

5\. Bring the dataset into R. The dataset is located at: https://daseh.org/data/kaggleMars_Dataset.csv. You can use the link, download it, or use whatever method you like for getting the file. Once you get the file, read the dataset in using `read_csv()` and assign it the name `mars`.

```{r 5response}
mars <- read_csv(file = "https://daseh.org/data/kaggleMars_Dataset.csv")
# OR
mars <- read_csv("https://daseh.org/data/kaggleMars_Dataset.csv")
# OR
url <- "https://daseh.org/data/kaggleMars_Dataset.csv"
mars <- read_csv(file = url)
# OR
download.file(
  url = "https://daseh.org/data/kaggleMars_Dataset.csv",
  destfile = "mars_data.csv",
  overwrite = TRUE,
  mode = "wb"
)
mars <- read_csv(file = "mars_data.csv")
```


6\. Import the data "dictionary" from https://daseh.org/data/kaggleMars_dictionary.txt. Use the `read_tsv()` function and assign it the name "key". 

```{r 6response}
key <- read_tsv(file = "https://daseh.org/data/kaggleMars_dictionary.txt")
# OR
download.file(
  url = "https://daseh.org/data/kaggleMars_dictionary.txt",
  destfile = "dict.txt",
  overwrite = TRUE,
  mode = "wb"
)
key <- read_tsv("dict.txt")
```


7\. You should now be ready to work with the "mars" dataset.

(a) Preview the data so that you can see the names of the columns. There are several possible functions to do this.
(b) Determine the class of the columns using `str()`. Write your answer as a comment inside the R chunk below.

```{r 7response}
str(mars)
#spc_tbl_ [3,197 × 13] (S3: spec_tbl_df/tbl_df/tbl/data.frame)
# $ earth_year           : num [1:3197] 2022 2022 2022 2022 2022 ...
# $ earth_date           : chr [1:3197] "01-26 UTC" "01-25 UTC" "01-24 UTC" "01-23 UTC" ...
# $ mars_date            : chr [1:3197] "Mars, Month 6 - LS 163deg" "Mars, Month 6 - LS 163deg" "Mars, Month 6 - LS 162deg" "Mars, Month 6 - LS 162deg" ...
# $ solar_day            : num [1:3197] 3368 3367 3366 3365 3364 ...
# $ max_ground_temp(degC): chr [1:3197] "-3" "-3" "-4" "-6" ...
# $ min_ground_temp(degC): chr [1:3197] "-71" "-72" "-70" "-70" ...
# $ max_air_temp(degC)   : chr [1:3197] "10" "10" "8" "9" ...
# $ min_air_temp(degC)   : chr [1:3197] "-84" "-87" "-81" "-91" ...
# $ mean_pressure(Pa)    : chr [1:3197] "707" "707" "708" "707" ...
# $ sunrise              : 'hms' num [1:3197] 05:25:00 05:25:00 05:25:00 05:26:00 ...
#  ..- attr(*, "units")= chr "secs"
# $ sunset               : 'hms' num [1:3197] 17:20:00 17:20:00 17:21:00 17:21:00 ...
#  ..- attr(*, "units")= chr "secs"
# $ UV_Radiation         : chr [1:3197] "moderate" "moderate" "moderate" "moderate" ...
# $ weather              : chr [1:3197] "Sunny" "Sunny" "Sunny" "Sunny" ...
# - attr(*, "spec")=
#  .. cols(
#  ..   earth_year = col_double(),
#  ..   earth_date = col_character(),
#  ..   mars_date = col_character(),
#  ..   solar_day = col_double(),
#  ..   `max_ground_temp(degC)` = col_character(),
#  ..   `min_ground_temp(degC)` = col_character(),
#  ..   `max_air_temp(degC)` = col_character(),
#  ..   `min_air_temp(degC)` = col_character(),
#  ..   `mean_pressure(Pa)` = col_character(),
#  ..   sunrise = col_time(format = ""),
#  ..   sunset = col_time(format = ""),
#  ..   UV_Radiation = col_character(),
#  ..   weather = col_character()
#  .. )
# - attr(*, "problems")=<externalptr> 
```


8\. How many data points (rows) are in the dataset? How many variables (columns) are recorded for each data point? 

```{r 8response}
dim(mars)
nrow(mars)
# There are 3197 data points in the dataset and 13 variables.
```


9\. Filter out (i.e., remove) measurements from earlier than 2015 (according to the Earth year), as well as any rows with missing data (NA). Replace the original "mars" object by reassigning the new filtered dataset to "mars". How many data points are left after filtering?

**Hint:** use drop_na() to remove rows with missing values.

```{r 9response}
mars <- drop_na(mars)
mars <- filter(mars, earth_year > 2014)
nrow(mars)
# OR
mars <- mars %>% drop_na() %>% filter(earth_year > 2014)
nrow(mars)

# There are 2393 measurements left after filtering by year.
```


10\. From this point on, work with the filtered "mars" dataset from the above question. A Martian year is equivalent to 668.6 sols (or solar days). Create a new variable (column) called "years_since_landing" that shows how many Martian years the Curiosity rover had been on Mars for each measurement (divide "solar_day" by 668.6). Check to make sure the new column is there.

**Hint:** use the `mutate()` function.

```{r 10response}
mars <- mars %>% mutate(years_since_landing = solar_day / 668.6)
# OR
mars <- mutate(mars, years_since_landing = solar_day / 668.6)
colnames(mars)
```


11\. What is the range of the maximum ground temperature ("max_ground_temp") of the dataset?

```{r 11response}
range(mars %>% pull(max_ground_temp))
# OR
gtemp_max_range <- pull(mars, max_ground_temp)
range(gtemp_max_range)
# OR
range(mars$max_ground_temp)
table(mars$max_ground_temp)

# The range is -67 degrees Celsius to 11 degrees Celsius. 
```


12\. Create a random sample with of atmospheric pressure readings from `mars`. To determine the column that corresponds to atmospheric pressure, check the "key" corresponding to the data dictionary that you imported above in question 6. Use `sample()` and `pull()`. Remember that by default random samples differ each time you run the code.

```{r 12response}
sample(pull(mars, mean_pressure), size = 20)
```


13\. How many data points are from days where the maximum ground temperature got above 0 degrees Celsius? What percent/proportion do these represent? Use:

- `filter()` and `nrow()`
- `group_by()` and `summarize()` or
- `sum()`

```{r 13response}
# How many data points are from days where the maximum ground temperature got above or equal to 0 degrees Celsius?
nrow(mars %>% filter(max_ground_temp >= 0))
# OR
mars %>%
  group_by(max_ground_temp >= 0) %>%
  summarize(total = n())
# OR
sum(mars$max_ground_temp >= 0)
# OR
table(mars$max_ground_temp >= 0)
# what percent/proportion do these represent?
nrow(mars %>% filter(max_ground_temp >= 0)) / nrow(mars)
# OR
mean(mars$max_ground_temp >= 0, na.rm=T)

# There are 218 data points from days where the ground temperature got above freezing. The percent of data points is 9.1%. 
```


14\. How many different UV radiation levels ("UV_Radiation") are there?

**Hint:** use `length()` with `unique()` or `table()`. Remember to `pull()` the right column.

```{r 14response}
mars %>%
  pull(UV_Radiation) %>%
  unique() %>%
  length()
# OR
length(unique(mars %>% pull(UV_Radiation)))
# OR
length(unique(mars$UV_Radiation))
# OR
table(unique(mars$UV_Radiation))


# 4 unique levels.
```


15\. How many different weather conditions ("weather") are reported?

```{r 15response}
mars %>%
  pull(weather) %>%
  unique() %>%
  length()

# 1 weather condition.
```


16\. Which UV radiation level had the highest maximum air temperature, and what was it?

**Hint:** Use  `group_by()` with `summarize()`.

```{r 16response}
mars %>%
  group_by(UV_Radiation) %>%
  summarize(mean = mean(max_air_temp))
```


17\. Extend on the code you wrote for question 16. Use the `arrange()` function to sort the output by maximum air temperature.

```{r 17response}
mars %>%
  group_by(UV_Radiation) %>%
  summarize(mean = mean(max_air_temp)) %>%
  arrange(desc(mean))
```


18\. How many measurements were taken on days when the UV radiation was "low" and the maximum air temperature was above freezing? Use:

- `filter()` and `count()`
- `filter()` and `tally()` or
- `sum()`

```{r 18response}
mars %>%
  filter(UV_Radiation == "low" & max_air_temp > 0) %>%
  tally()
# OR
mars %>%
  filter(UV_Radiation == "low" & max_air_temp > 0) %>%
  count()
# OR
sum(mars$UV_Radiation == "low" & mars$max_air_temp > 0)

# A total of 3 days.
```


19\. How many days was the UV radiation was "high" or "very high"? use:

- `filter()` and `count()`
- `filter()` and `tally()` or
- `sum()`

```{r 19response}
mars %>%
  filter(UV_Radiation == "high" | UV_Radiation == "very_high") %>%
  count()
# OR
mars %>%
  filter(UV_Radiation %in% c("high", "very_high")) %>%
  count()
# OR
sum(mars$UV_Radiation == "high" | mars$UV_Radiation == "very_high")
# OR
sum(mars$UV_Radiation %in% c("high", "very_high"))

# A total of 1125 days.
```


20\. Select all columns in "mars" where the column names starts with "min" (using `select()` and `starts_with()`. Then, use `colMeans()` to summarize across these columns.

```{r 20response}
mars %>%
  select(starts_with("min")) %>%
  colMeans()
```


21\. Using "mars", create a new binary (TRUEs and FALSEs) column to indicate if the day's maximum air temperature was above freezing. Call the new column "above_freezing".

```{r 21response}
mars <- mars %>% mutate(above_freezing = (max_air_temp > 0))
```


22\. What is the average atmospheric pressure for days that have an air temperature above freezing and UV radiation level of "moderate"? How does this compare with days that do NOT fit these criteria?

```{r 22response}
mean_mod_warm <- mars %>%
  filter(above_freezing == TRUE & UV_Radiation == "moderate") %>%
  summarize(mean = mean(mean_pressure)) %>%
  pull()

mean_not_mod_warm <- mars %>%
  filter(above_freezing != TRUE | UV_Radiation != "moderate") %>%
  summarize(mean = mean(mean_pressure)) %>%
  pull()

# Days that are above freezing with UV level of "moderate" have an average atmospheric pressure of 820.7 Pa while days not fitting this criteria have an average atmospheric pressure of 826.6 Pa.
```


23\. Among days with a "moderate" UV level that are above freezing, what is the distribution of the earth year in which these days occurred?

```{r 23response}
mod_warm <- mars %>% filter(UV_Radiation == "moderate" & above_freezing == TRUE)
mod_warm %>%
  group_by(earth_year) %>%
  select(earth_year) %>%
  table()
# OR
mod_warm <- mars %>% filter(UV_Radiation == "moderate" & above_freezing == TRUE)
mod_warm %>%
  group_by(earth_year) %>%
  count()
# OR
mod_warm <- mars %>% filter(UV_Radiation == "moderate" & above_freezing == TRUE)
mod_warm %>%
  group_by(earth_year) %>%
  tally()
```


24\. How many days (using `filter()` or `sum()` ) have a maximum ground or air temperature above zero and have a UV level of "high" or "very_high"?

```{r 24response}
sum((mars$max_ground_temp > 0| mars$max_air_temp > 0) & (mars$UV_Radiation == "high" | mars$UV_Radiation == "very_high"))
# OR
sum((mars$max_ground_temp > 0| mars$max_air_temp > 0) & mars$UV_Radiation %in% c("high", "very_high"))
# OR
mars %>%
  filter((mars$max_ground_temp > 0| mars$max_air_temp > 0) & mars$UV_Radiation %in% c("high", "very_high")) %>%
  count()

# A total of 886 days. 
```


25\. Make a boxplot (`boxplot()`) that looks at earth year ("earth_year") on the x-axis and minimum air temperature ("min_air_temp") on the y-axis.

```{r 25response}
boxplot(mars %>% pull(min_air_temp) ~ mars %>% pull(earth_year))
```


26\. Knit your document into a report.

You use the knit button to do this. Make sure all your code is working first!
