### Announcement

- Lectures will be online with zoom recordings

  - <https://tulane.zoom.us/j/94892763737?pwd=VTlmMStLd3hUeUhEY0UxdUZJVnk3UT09>

- Introduce yourself on Canvas [Discussion](https://tulane.instructure.com/courses/2238421/discussion_topics/13241432?module_item_id=30871904)

- Email me your GitHub user name and accept the invitation to course organization

- HW1 posted (due in 3 weeks on Oct 1st, 2021)

  - learn from the past: start early

- Project description (one page) due in two weeks on Sept. 24, 2021

### First functions to learn

|symbol | use |
| ------| ----|
| ? | get documentation |
| str | show structure |

```{r}
test.str <- 1:6
str(test.str)
```


### Locating and deleting objects:
The commands "objects()" and "ls()" will provide a list of every object that you've created in a session.

```{r}
objects()

ls()
```

The "rm()" and "remove()" commands let you delete objects (tip: always clearn-up your workspace as the first command)

```{r}
rm(list=ls())  # clean up workspace
```

### Vectors

Many commands in R generate a vector of output, rather than a single number.

The "c()" command: creates a vector containing a list of specific elements.

Example 1

```{r}
c(7, 3, 6, 0)
c(73:60)
c(7:3, 6:0)
c(rep(7:3, 6), 0)
```

Example 2
The command "seq()" creates a sequence of numbers.
```{r}
seq(7)
seq(3, 70, by = 6)
seq(3, 70, length = 6)
```


### Operations on vectors

Use brackets to select element of a vector.

```{r}
x <- 73:60
x[2]
x[2:5]
x[-(2:5)]
```

Can access by "name" (safe with column/row order changes)

```{r}
y <- 1:3
names(y) <- c("do", "re", "mi")
y[3]
y["mi"]
```

### Matrix

matrix() command creates a matrix from the given set of values

```{r}
matrix.example <- matrix(rnorm(100), nrow = 10, ncol = 10, byrow = TRUE)
matrix.example
```


### R commands on vector/matrix

| command | usage |
|---------|-------|
| sum()   | sum over elements in vector/matrix |
| mean()  | compute average value |
|sort() | sort all elements in a vector/matrix |
| min(), max() | min and max values of a vector/matrix|
| length() | length of a vector/matrix |
|summary() | returns the min, Q1, median, mean, Q3, and max values of a vector |
| dim() | dimension of a matrix |
| cbind() | combine a sequence of vector, matrix or data-frame arguments and combine by columns |
| rbind() | combine a sequence of vector, matrix or data-frame arguments and combine by rows |
| names() | get or set names of an object |
| colnames() | get or set column names of a matrix-like object |
| rownames() | get or set row names of a matrix-like object |
<!-- | sample(x, size, replace = FALSE, prob = NULL) | takes a random sample from a vector with or without replacement| -->

```{r}
sum(matrix.example)
mean(matrix.example)
sort(matrix.example)
summary(matrix.example)
```

**Exercise**
Write a command to generate a random permutation of the numbers between 1 and 5 and save it to an object.


<!--
```{r}
order(runif(5))
sample(1:5, 5)
```
-->

### Comparison (logic operator)
|symbol | use |
|-------|---------|
| != | not equal |
| == | equal |
| >  | greater |
| >= | greater or equal |
| <  | smaller |
| <= | smaller or equal |
| is.na | is it "Not Available"/Missing |
| complete.cases | returns a logical vector specifying which observations/rows have no missing values |
| is.finite | if the value is finite |
| all | are all values in a logical vector true? |
| any | any value in a logical vector is true? |

```{r}
test.vec <- 73:68
test.vec

test.vec < 70

test.vec > 70

test.vec[3] <- NA
test.vec

is.na(test.vec)

complete.cases(test.vec)

all(is.na(test.vec))
any(is.na(test.vec))
```

Now let's do a test of accuracy for doubles in R.
Recall that for _Double_ precision, we get approximately $\log_{10}(2^{52}) \approx 16$ decimal point for precision.

```{r}
test.exponent <- -(7:18)
10^test.exponent == 0
1 - 10^test.exponent == 1
7360 - 10^test.exponent == 7360
73600 - 10^test.exponent == 73600
```

### Other operators

%in%, match

```{r}
test.vec
66 %in% test.vec

match(66, test.vec, nomatch = 0)

70 %in% test.vec

match(70, test.vec, nomatch = 0)

match(70, test.vec, nomatch = 0) > 0 # the implementation of %in%

```


### Control flow

These are the basic control-flow constructs of the R language. They function in much the same way as control statements in any Algol-like (Algol short for "Algorithmic Language") language. They are all reserved words.

| keyword | usage |
| ------- | ----- |
| if | **if**(_cond_) _expr_ |
| if-else | **if**(_cond_) _cons.expr_ **else** _alt.expr_ |
| for  | **for**(_var_ **in** _seq_) _expr_ |
| while | **while**(_cond_) _expr_ |
| break | breaks out of a _for_ loop |
| next | halts the processing of the current iteration and advances the looping index|


### Define a function

Read [Function](http://adv-r.had.co.nz/Functions.html) section from Advanced R by Hadley Wickham.
We will visit functions in more details.

```{r}
DoNothing <- function() {
  return(invisible(NULL))
}
DoNothing()
```

In general, try to avoid using loops (vectorize your code) in R.
If you have to loop, try using **for** loops first.
Sometimes, **while** loops can be dangerous (however, a smart _compiler_ should detect this).

```{r}
DoBadThing <- function() {
  result <- NULL
  while(TRUE) {
    result <- c(result, rnorm(100))
  }
  return(result)
}
# DoBadThing()
```
