# Activity 08/30/2021

## STAT 445 / 645 -- Section 1001 <br> Instructor: Colin Grudzien<br>

## Instructions:
We will work through the following series of activities as a group.  Follow the instructions in each sub-section when the instructor assigns you to a breakout room.

## Activities:

### Activity 1: Reviewing Factors 

We will suppose that we wish to analyze a new set of cat data that a friend gave us:
```
coat,   weight,     likes_string
calico, 2.1,        1
black,  5.0,        0
tabby,  3.2,        1
tabby,  2.3 or 2.4, 1
```

Our friend was uncertain about the weight of the last cat and placed two values into the CSV.
We suppose that this is written in the file "feline-data_v2.csv" which we will read with "read.csv()". Download the feline-data-v2.csv from Canvas and then run the following code

```{r}
cats_from_file <- read.csv(file="feline-data_v2.csv")
cats_from_file$weight
```

When R read the inhomogeneous data in the weights column, it first converted the values into character type; when the character vector was seen by R in a dataframe, it then converted it automatically to a **factor vector**. Converting characters to factors automatically can be suppressed with additional arguments:
```{r }
cats_from_file <- read.csv(file="feline-data_v2.csv", stringsAsFactors=FALSE)
cats_from_file$weight
```

However, this illustrates in general how erroneously entered data can cause many issues with type conversions.


#### Question 1:
Suppose we know that the true weight of the fourth cat was actually 2.35kg.  Can you fix the dataframe to contain the correct data?  Try saving the correct dataframe and re-open it using our I/O commands -- does the data come out as expected?

```{r, eval=FALSE}

```

#### Question 2:
Let's imagine that 1 cat year is equivalent to 7 human years.
  1. Create a vector called `human_age` by multiplying `cats$age` by 7.
  2. Convert `human_age` to a factor.
  3. Convert `human_age` back to a numeric vector using the `as.numeric()` function. 
Now divide it by 7 to get the original ages back. Explain what happened.

```{r, eval=FALSE}

```


### Debrief: discuss the questions
We will discuss the questions from activity 1 as a class.


### Activity 2: A realistic dataframe
Through much of the class, we will call data from different libraries in R. For this lesson we will consider the ``gapminder`` data. We start by importing this from R:
```{r}
require(gapminder)
```

When we start looking at new data, best practice is to start interrogating it to see the data types, the number of cases and the different variables in each case:
```{r }
str(gapminder)
summary(gapminder)
```

We also often benefit from looking at a sub-slice of the data to "feel" what kind of data we are working with. This is commonly done with the ``head()`` function; this will extract the leading rows of the dataframe for examination:
```{r eval=FALSE}
head(gapminder)
```


Similarly, we can use the ``tail()`` function to examine the trailing rows:
```{r eval=FALSE}
tail(gapminder)
```


#### Question 1:
We might be interested in a particular country, let's say India. Discuss with your peers, how can we create a sub-dataframe based on the cases corresponding to India alone.  Consider how you would fill in the following lines of code to complete this
```{r, eval=FALSE}
india_index <-
india_dataframe = gapminder[india_index,]
```

Try running the ```head()``` and ```tail()``` functions to confirm you have the data you want.

#### Question 2:

In the above, we have constructed a logical vector for the purpose of indexing the <b>rows</b> which correspond to India.
Any row which contains the factor level ``India`` in the ``country`` factor vector will correspond to a ``TRUE`` in the logical vector ``india_index``.  Any row which does not contain the factor level ``India`` will respectively correspond to a ``FALSE``.

R has several different kinds of plotting commands and libraries; for simple plots, intended as exploratory analysis, we often will use the "base" R plotting. For more advanced control and formatting, we will typically use a more sophisticated library, such as ``ggplot2``; learning to use advanced plotting will be in the homework assignment.
  
If we want to create a quick exploratory "x-y" plot of some relationship, this can be done with the ``plot()`` function.  For example, we will plot the change of life expectancy over time in India:

```{r fig.width=24, fig.height=8, eval=FALSE}
plot(india_dataframe$year, india_dataframe$lifeExp) 
```
  
In the last command, we can adjust labels and plot sizes with additional arguments in the plot function; these arguments and "keywords" can be found in the help file for plot, using ``?plot``.
```{r fig.width=24, fig.height=8, eval=FALSE}
par(mai=c(1.5,1.5,.5,.5), mgp=c(3,0,0))
plot(india_dataframe$year, india_dataframe$lifeExp, cex=3, cex.lab=3, cex.axis=2) 
```
  
Now, try using the help file to look up the arguments for axis-labels as well as the title.  Can you make this plot more professional by providing an informative title and axis labels?


#### Question 3:

Try making an original plot from scratch with the `gapminder` data.  Use any of the variables of your choice to express some interesting relationship that you observe by plotting two variables against each other.  Try to include a clear title expressing the relationship and axis labels so the reader can understand what they are seeing.


### Debrief: discuss the questions
We will discuss the questions from activity 2 as a class.


### Activity 3: vectors and matrices


#### Question 1:
Make a vector with the numbers 1 through 26.  Multiply the vector by 2, and give the resulting vector elements the names A through Z (hint: there is a built in vector called `LETTERS`).


#### Question 2:
We can declare a matrix full of zeros:

```{r eval=FALSE}
matrix_example <- matrix(0, ncol=6, nrow=3)
matrix_example
```

And similar to other data structures, we can ask things about our matrix:

```{r eval=FALSE}
class(matrix_example)
typeof(matrix_example)
str(matrix_example)
dim(matrix_example)
nrow(matrix_example)
ncol(matrix_example)
```

What do you think will be the result of
`length(matrix_example)`?
Try it.
Were you right? Why / why not?

#### Question 3:
Make another matrix, this time containing the numbers 1:50, with 5 columns and 10 rows.
Did the `matrix` function fill your matrix by column, or by row, as its default behavior?
See if you can figure out how to change this.
(hint: read the documentation for `matrix`!)

#### Question 4:

Consider the R output of the matrix below:
```{r eval=FALSE}
matrix(c(4, 1, 9, 5, 10, 7), ncol = 2, byrow = TRUE)
```
Examine each command below and try to figure out what matrices these commands will produce.

  1. `matrix(c(4, 1, 9, 5, 10, 7), nrow = 3)`
  2. `matrix(c(4, 9, 10, 1, 5, 7), ncol = 2, byrow = TRUE)`
  3. `matrix(c(4, 9, 10, 1, 5, 7), nrow = 2)`
  4. `matrix(c(4, 1, 9, 5, 10, 7), ncol = 2, byrow = TRUE)`
  
### Debrief: discuss the questions
We will discuss the questions from activity 3 as a class.
