```{r global options, include=FALSE}
knitr::opts_chunk$set(echo = TRUE)
```

```{r, message=F}
library(sf)  
library(terra)  
library(tidyverse)  
library(spData)
library(magrittr)
```

## Attribute Data Operations

Attribute data is non-spatial information associated with geographic (geometry) data. Understanding how to manipulate attribute data in vector and raster datasets is important because you will likely be performing operations on these data throughout your analysis. Fortunately, in 'sf' objects these operations are analagous to working with data frames. For raster objects, each cell contains a single attribute value so it is important that each raster layer is consistently defined.

***

## Vector Attribute Manipulation

The most significant difference between data frames and 'sf' objects is that 'sf' objects include the 'geometry' column. A useful feature of this column is that it is "sticky" and will remain appended to the attribute data unless explicitly removed. 


For example, read in the 'world' dataset and then select out a single column.

```{r}
summary(world)

```
NOTE: It is useful to index to the package specifically when using certain functions like select(). This is especially true when working with 'sf' and 'terra' which share a number of function names.

Which columns remain after using select()?

If you really need to remove the 'geometry' column from an 'sf' object then you can use the conveniently named st_drop_geometry() function. Removing the 'geometry' column can be useful because operations on the attribute data alone can sometimes be faster. However, it is usually helpful to keep the 'geometry' column included and there shouldn't be any instances during this workshop when you'll need to drop it.


## Vector Attribute Subsetting

Vector attribute subsetting can be accomplished using the base R operators such as [] and subset() or the dplyr functions filter(), slice(), or select().

Base R and dplyr functions both work well for subsetting 'sf' objects while maintaining them as 'sf' objects. However, if you use operators such as $ or [[]] or the dplyr function pull() then you should expect to receive vectors rather than 'sf' objects. Vectors, by definition, will only store information from a single column which means you will lose the 'geometry' column.

Use 'world' to create a new 'sf' object that only includes data on name, continent, region, area, and population for countries that have an area greater than 50,000 km^2.

```{r}

```


## Vector Attribute Aggregation

A common part of a data analysis workflow is to group and summarize data according to grouping variables (i.e. aggregation). The 'tidy' method of programming in R provides an excellent workflow and we recommend using the pipe operator (%>%) as well. Pipes are efficient and easier to read than the base R equivalent of subsetted functions. 

Here is an example of a pipe that will group the 'world' dataset by 'continent' and then calculate the total population

```{r}
world_cont_pop <- world %>% 
  group_by(continent) %>%
  summarize(pop = sum(pop, na.rm=T))
world_cont_pop
```
Let's try to write a pipe that only includes Asia, Europe, and Africa and summarizes each continent by total area.

```{r}

```

Here is another slightly more involved example. If you have time, then add a comment to each line to describe what it does.
```{r}
world_agg <- world %>% 
  st_drop_geometry() %>%                      
  dplyr::select(pop, continent, area_km2) %>% 
  group_by(continent) %>%                     
  summarize(Pop = sum(pop, na.rm = TRUE), Area = sum(area_km2), N = n()) %>%
  mutate(Density = round(Pop / Area)) %>%     
  top_n(n = 3, wt = Pop) %>%                   
  arrange(desc(N))                            
```


## Vector Attribute Joining

Another common part of a data analysis workflow will be joining different datasets. 'dplyr' provides us with a number of useful functions for this such as left_join(), inner_join(), and full_join() and these same functions work with 'sf' objects as well.

'spData' includes another dataset called 'coffee_data'. Try to join 'world' and 'coffee_data' using one of the dplyr join functions.

```{r}

```

Did it work? Note that joins will only work if there is a common column name between the two objects being joined.

If you use left_join() then it is also important to note that the result of this function will usually match the formatting of the first argument. (i.e. left_join(world, coffee_data) will return an 'sf' object because 'world' was an 'sf' object but left_join(coffee_data, world) will return a data frame)

## Creating Attributes

Another important part of your workflow might include creating new columns based off of data from exisiting columns. The 'dplyr' functions mutate() and transmute() will aid you in accomplishing this. 

Describe what this code chunk does and then add another column that log transforms the population
```{r}
world %>% 
  mutate(pop_dens = pop / area_km2)
```

***

## Manipulating Raster Objects

Raster objects can not be manipulated like vector objects since these represent continuous surfaces rather than geometric objects (points, lines, and polygons). For raster objects, we will primarily use the [] operators for subsetting. First, we can create a couple raster objects that we can work with.

This chunk creates a 6x6 raster that will represent elevation (continuous data).
```{r}
elev = rast(nrows = 6, ncols = 6, resolution = 0.5, 
            xmin = -1.5, xmax = 1.5, ymin = -1.5, ymax = 1.5,
            vals = 1:36)
```

This chunk creates another 6x6 raster that represents grain sizes (categorical data).
```{r}
grain_order = c("clay", "silt", "sand")
grain_char = sample(grain_order, 36, replace = TRUE)
grain_fact = factor(grain_char, levels = grain_order)
grain = rast(nrows = 6, ncols = 6, resolution = 0.5, 
             xmin = -1.5, xmax = 1.5, ymin = -1.5, ymax = 1.5,
             vals = grain_fact)
```

Cell values can be obtained and overwritten using the [] operators.
```{r}
elev[1,1]
elev[1,1] <- 0
elev[1,1]
```

c() can be used to combine layers to make a multi-layer raster
```{r}
multi <- c(elev,grain)
```

## Summarizing raster objects

'terra' includes helpful functions to gather descriptive statistics from raster objects. A few of these include some familiar functions such as boxplot(), hist(), and summary()

Try a few of these out and compare with your neighbor. ('grain' had cells that were randomly assigned so you should expect different answers for that raster)
```{r}

```

***

For these exercises we will use the us_states and us_states_df datasets from the spData package:

us_states is a spatial object (of class sf), containing geometry and a few attributes (including name, region, area, and population) of states within the contiguous United States. us_states_df is a data frame (of class data.frame) containing the name and additional variables (including median income and poverty level, for the years 2010 and 2015) of US states, including Alaska, Hawaii and Puerto Rico. The data comes from the United States Census Bureau, and is documented in ?us_states and ?us_states_df.

E1. Create a new object called us_states_name that contains only the NAME column from the us_states object. What is the class of the new object and what makes it geographic?


```{r}

```


E2. Select columns from the us_states object which contain population data. Obtain the same result using a different command (bonus: try to find three ways of obtaining the same result). Hint: try to use helper functions, such as contains or starts_with from dplyr (see ?contains).

```{r}

```


E3. Find all states with the following characteristics (bonus find and plot them):

Belong to the Midwest region.
Belong to the West region, have an area below 250,000 km2and in 2015 a population greater than 5,000,000 residents (hint: you may need to use the function units::set_units() or as.numeric()).
Belong to the South region, had an area larger than 150,000 km2 or a total population in 2015 larger than 7,000,000 residents.

```{r}

```


E4. What was the total population in 2015 in the us_states dataset? What was the minimum and maximum total population in 2015?

```{r}

```


E5. How many states are there in each region?

```{r}

```


E6. What was the minimum and maximum total population in 2015 in each region? What was the total population in 2015 in each region?

```{r}

```


E7. Add variables from us_states_df to us_states, and create a new object called us_states_stats. What function did you use and why? Which variable is the key in both datasets? What is the class of the new object?

```{r}

```


E8. us_states_df has two more rows than us_states. How can you find them? (hint: try to use the dplyr::anti_join() function)

```{r}

```


E9. What was the population density in 2015 in each state? What was the population density in 2010 in each state?

```{r}

```


E10. How much has population density changed between 2010 and 2015 in each state? Calculate the change in percentages and map them.

```{r}

```


E11. Change the columns’ names in us_states to lowercase. (Hint: helper functions - tolower() and colnames() may help.)

```{r}

```


E12. Using us_states and us_states_df create a new object called us_states_sel. The new object should have only two variables - median_income_15 and geometry. Change the name of the median_income_15 column to Income.

```{r}

```


E13. Calculate the change in the number of residents living below the poverty level between 2010 and 2015 for each state. (Hint: See ?us_states_df for documentation on the poverty level columns.) Bonus: Calculate the change in the percentage of residents living below the poverty level in each state.

```{r}

```


E14. What was the minimum, average and maximum state’s number of people living below the poverty line in 2015 for each region? Bonus: What is the region with the largest increase in people living below the poverty line?

```{r}

```


E15. Create a raster from scratch with nine rows and columns and a resolution of 0.5 decimal degrees (WGS84). Fill it with random numbers. Extract the values of the four corner cells.

```{r}

```


E16. What is the most common class of our example raster grain (hint: modal())?

```{r}

```


E17. Plot the histogram and the boxplot of the data(dem, package = "spDataLarge") raster.

```{r}

```

