---
title: "Learn R - Monday AM"
output: html_notebook
---

This is an [R Markdown](http://rmarkdown.rstudio.com) Notebook. When you execute code within the notebook, the results appear beneath the code. 

Try executing this chunk by clicking the *Run* button within the chunk or by placing your cursor inside it and pressing *Ctrl+Shift+Enter*. 

Code chunks are surrounded by the lines:
` ```{r} ... ```  `
Also remember that `# everything that follows a number sign on a line is ignored by R - this text is for the humans!`

```{r}
## R source file from Monday morning
### Introduction to Objects, Functions, & Workspaces

23+19 # R is really just a fancy calculator that will do calculations
```
``` {r}
a <- 23 + 19  # you can save calculated values into memory by assigning the value to an object. Here our object is named "a". Assign values to objects using the "<-" (less than sign followed by hyphen) symbol. In RStudio you can get this number quickly using the keyboard shortcut Alt + -
a  # this simply prints out the value of a
```

To create a vector (multiple values in an object) use the function c()

``` {r vectors}
numbers <- c(1,5,9,3,7) # Here we create a numeric vector
letters <- c("a","b","d")  # This is a character vector
words <- c("cat", "hat", "thing1", "thing2") # Another character vector
```

```{r matrix}
mat1 <- matrix(c(1,5,9,8,12,10), nrow = 3, ncol=3) # Use the function matrix() to create a matrix, give it a vector of numbers and indicate how many rows and columns your matrix should have
str(mat1) # str() is a handy function for giving you information about an object
```
```{r}
mat1  # this simply prints out the matrix called mat1
```

```{r}
class(mat1)  # the function class() gives information on the type of data that make up mat1
```
```{r}
class(letters) # Use class() and str() on the vector called "letters" also to see the difference in what is returned
str(letters)
```

## Reading data in from comma-delimited file

```{r}
dat <-read.table("RData.csv", header = TRUE, sep= ',') # this will read in data from a file and place it into a data.frame object; header = TRUE means that our first row gives column names, sep = ',' indicates that data values are separated by commas
dat <- read.csv("RData.csv") # This line is equivalent to the one above; read.csv() is a special case of read.table that with the defaults for header and sep that we passed to read.table() in the line above
str(dat) ### Check the data!!
head(dat)
```

## Indexing data.frames
Pulling out parts of the data.frame - specific columns, rows, or elements is done using the function "[" (a square bracket)
***Note that the syntax of this is always [rows, columns]

```{r}
part1 <- dat[,1:4] ## Here we take columns 1 through 4 from the data.frame "dat" and place it into a new object (data.frame) we call 'part1'
str(part1) # check it out
```

The easist way to specify particular rows and columns we want is to use the function `subset()`
Note the shortcut for indexing also introduced here. We can refer to a particular variable (column) in a data.frame using the `$` operator, as in data.frame$variable.name

```{r}
# In the code below we place into a new data.frame the result from running the function subset, passing it the arguments (in order): dat (= data.frame name), dat$Species == "woodfrog" (= condition for deciding which rows to keep), c(dat$Species, dat$trtmt, dat$fish, dat$parasite) (= a vector of the columns we want to keep, using column names to identify them)
woodfrog3 <- subset(dat, subset = dat$Species == "woodfrog", select = c(dat$Species, dat$trtmt, dat$fish, dat$parasite)) 
```

We can also use the `data.frame()` function to create a new data.frame from columns in dat
```{r}
part1 <- data.frame(dat$Species, dat$trtmt, dat$fish, dat$parasite)
```
When creating a new data.frame it is also easy to re-name the variables (columns)
```{r}
part1a <- data.frame("spp" = dat$Species, "trt" = dat$trtmt, "fish"= dat$fish, "par" = dat$parasite)
```

Note that above, I had to identify each variable using both its data.frame name and its column name. An alternative to doing this is to use the `with()` function to first specify which data.frame R should use for the functions that follow.
```{r}
with(dat, 
		 part1a <- data.frame("spp"= Species, "trt" = trtmt, "fish"=fish, par = "parasite")
) # note how I can use newlines and spacing to make this easier to read for humans and it does not affect how it runs in R
```

We can also select non-contiguous columns by passing the indexing operator `[` a vector of column numbers
```{r}
part2 <- dat[,c(6:8,10:12)] # here we indicate we want column numbers 6-8 and 10-12 (i.e., 6,7,8,10,11,12)

# Recognize that using the c() function in the code above is a shortcut for the following 2 lines: we create a vector and pass it to the column argument of [
sel <- c(6:8, 10:12)
part2a <- dat[,sel]
```

We can combine data.frames to create a larger data.frame, as long as the number of rows in the two data.frames is equal
```{r}
tog <- data.frame(part1, part2) # create a new data.frame called 'tog'
str(tog) # checkout the new data.frame
```
Other ways to create new data.frames:
```{r}
tog1 <- dat[,c(-5:-7)] # create a data.frame using all the columns in data.frame 'dat' EXCEPT columns 5, 6, and 7
tog2 <- cbind(part1, part2) # join variables with equal numbers of rows using the function cbind() (column-bind)
```
Note that cbind with 2 numeric vectors will give you a matrix, not a data.frame
```{r}
num1 <- c(1:6); num2 <- c(7:12) # you can put two commands on a single line if you separate them with a semi-colon (i.e., a semi-colon = a line return)
cbind(num1, num2) -> mat # you can also create a new object and then assign it to an object name using a forward arrow
class(mat)
```
Use `data.frame()` to force numeric vectors to be placed in a data.frame object
```{r}
mat1 <- data.frame(num1,num2) # create a data.frame 
class(mat1) # check I've made data.frame
```
We can select rows using `[` if we place row numbers we want before the comma
```{r}
samp1 <- dat[1:30,] # save rows 1 to 30 of dat into data.frame called samp1
samp2 <- dat[40:74,] # as above, but rows 40 to 74 and into samp2

combined <- rbind(samp1,samp2) # as long as our data.frames have the same variable names (you can check this with the function names) then we can combine the rows using rbind (row-bind)
class(combined) # check what we get
str(combined)
```

Notice you can also do more complex conditionals when using the indexing functions
```{r}
bulls <- part1a[part1a$spp == "bullfrog",] # create a data.frame of only those individuals (rows) that are species = bullfrogs
bulls.fish <- part1a[part1a$spp == "bullfrog" & part1a$trt == "fish",] # create a data.frame that is only bullfrogs in treatment "fish"

# Below we use the subset() function again to create a new data.frame that contains only rows where flicksPOST > 0 and species is woodfrog or bullfrog and we keep all columns except the column called flicksPRE
newdat <- subset(dat, subset = flicksPOST > 0 & (Species == "woodfrog"| Species == "bullfrog"), select = -flicksPRE)

```

