-
Notifications
You must be signed in to change notification settings - Fork 1
/
P2-programming-basics.Rmd
66 lines (47 loc) · 2.24 KB
/
P2-programming-basics.Rmd
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
---
title: "Practice 2 - Programming Basics"
output:
html_document:
number_sections: false
toc: no
---
```{r setup, echo=FALSE, message=FALSE, warning=FALSE}
rm(list=objects()) # start with a clean workspace
source("knitr_setup.R")
```
# Basic functions
Try out a few common, basic functions to learn what they do and how they work:
- Square root: `sqrt(64)` (you could also do this: `64^0.5`)
- Exponential: `exp(0)`, `exp(1)`, `exp(-10)`,
- Natural log: `log(10)`, log(1), `log(0)`, `log(-1)`, `log(exp(2))`
- Factorial: `factorial(1)`, `factorial(5)`, `factorial(-1)`, `factorial(0)`
- Round: `round(3.1415)`, `round(3.1415, digits=2)`
- Absolute value: `abs(-1)`, `abs(1)`
Here's a couple more to foreshadow where we'll be going:
- Type `rep("hello!", 100)` and take a look at the output. What does `rep()` do?
- Type `hist(x=rnorm(300))` and see what happens. What do you think the `hist()` function does? What about the `rnorm()` function? How could you find out more about each function?
# Objects
Make some objects using the following assignments:
```{r}
w <- 1
x <- 1
y <- 2
z <- 3
```
Using only these objects, try writing code to answer the following questions:
- Write a statement comparing the magnitude of `z` to `w` that returns `TRUE`
- Write a statement comparing the magnitude of `x` to `w` that returns `TRUE`
- Fill in the correct relational operators to make this statement return `TRUE`: `(x __ y) & (z __ y)`
# Data types
Try answering some of these questions **before** running any code - reason through the commands, then run the code and see if you were correct:
- What happens when you try to do math with a string: `"3" / 4`
- What do you think R will return if we divide infinity by a really big number: `Inf / 10^20`
- Why doesn't the following code return `TRUE` (Hint: [read ahead](L3-functions.html#7_tips) to find out):
```{r}
(0.1 + 0.2) == 0.3
```
---
**Page sources**:
Some content on this page has been modified from other courses, including:
- CMU [15-112: Fundamentals of Programming](http://www.kosbie.net/cmu/spring-17/15-112/), by [David Kosbie](http://www.kosbie.net/cmu/) & [Kelly Rivers](https://hcii.cmu.edu/people/kelly-rivers)
- Danielle Navarro's website ["R for Psychological Science"](https://psyr.org/index.html)