---
output:
prettydoc::html_pretty:
theme: architect
highlight: vignette
---
# R for Beginners: Examples of Simple Commands
## Problem 1
Use R as a calculator to compute the following values.
(a) $9 + 3(6 - 4)$
```{r}
9 + 3 * (6 - 4)
```
(b) $\sqrt{\frac{900}{12}}$
```{r}
sqrt(900 / 12)
```
(c) $ln(14^2)$, where $ln$ is the natural logarithm.
```{r}
log(14^2)
```
(d) $e(1)$, which should give Euler's number.
```{r}
exp(1)
```
(e) Calculate the absolute value of $13 - 22/1.2$
```{r}
abs(13 - 22 / 1.2)
```
## Problem 2
Create the following vectors in R.
(a) `v1`, which has the elements (5,7,3)
```{r}
v1 <- c(5, 7, 3)
v1
```
(b) `v2`, which has the elements (0,5,10,15,...,100)
```{r}
v2 <- seq(0, 100, by = 5)
v2
```
(c) `v3`, which has the elements (Yugoslavia,Yugoslavia,Canada,Canada,Czech Republic, Czech Republic,Croatia,Croatia,Hungary,Hungary,USA,USA)
```{r}
v3 <- c("Yugoslavia", "Yugoslavia", "Canada", "Canada", "Czech Republic",
"Czech Republic", "Croatia", "Croatia", "Hungary", "Hungary", "USA", "USA")
v3
```
(d) `v3.1`, which is the same as `v3` above but uses the repeat command.
```{r}
v3.1 <- rep(c("Yugoslavia", "Canada", "Czech Republic", "Croatia", "Hungary", "USA"),
each = 2)
v3.1
```
(e) `v4`, which has the elements (2018,2012,2010,...,1918)
```{r}
v4 <- c(2018, seq(2012, 1918, by = -2))
v4
```
(f) `v5`, a vector whose values start at 20, end at 0, and contains 36 evenly spaced elements
```{r}
v5 <- seq(20, 0, length.out = 36)
v5
```
## Problem 3
For each of the following questions, use R to find the answer.
(a) What are the 7th, 8th, and 12th elements of `v5`?
```{r}
v5[c(7, 8, 12)]
```
(b) Which elements of `v5` are less than or equal to 13.5?
```{r}
which(v5 <= 13.5)
```
(c) What is the value of each of the elements of `v5` that is less than or equal to 13.5?
```{r}
v5[v5 <= 13.5]
```
(d) What is the percentage of elements of `v5` that is less than 3.4?
```{r}
mean(v5 < 3.4) * 100
```
(e) Which elements of `v5` are greater than 10 *and* less than 13?
```{r}
which(v5 > 10 & v5 < 13)
```
(f) What are the values of the elements of `v5` that are greater than 10 and less than 13?
```{r}
v5[v5 > 10 & v5 < 13]
```
## Problem 4
Draw a pie chart with two slices - the values of `v5` that are greater than, and those that are less than 15. In other words, your pie chart should show the relative percentage of values in `v5` that are greater than 15 versus those that are less than 15. Bonus point: make one of the pie slices the color `salmon` and the other slice the color `gold`.
```{r}
slices <- table(v5 > 15)
lbls <- c("Less than 15", "Greater than 15")
pie(slices, labels = lbls, col = c("salmon", "gold"))
```
## Problem 5
Find the following for the vector `v1` (which you created above):
(a) mean
```{r}
mean(v1)
```
(b) median
```{r}
median(v1)
```
(c) range
```{r}
range(v1)
```
(d) standard deviation
```{r}
sd(v1)
```