-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path03_functions.qmd
More file actions
386 lines (238 loc) · 9.73 KB
/
03_functions.qmd
File metadata and controls
386 lines (238 loc) · 9.73 KB
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
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
# Functions
## Basics
### What is a function?
Informally, a function is anything that takes input(s) and gives one defined output. There are always three main parts:
- The input ($x$ values, or each value in the domain)
- The relationship of interest
- The output ($y$ values, or a unique value in the range)
](images/function_machine.png){#fig-function-machine width="400"}
::: callout-note
"$f(x) = \space ...$ is the classic notation for writing a function, but we can also use"$y = \space ...$". This is because $y$ is"a function of" $x$, so $y=f(x)$.
:::
Let's take a look at an example and break down the structure:
$$f(x) = 3x + 4$$
- $x$ is the *input* (some value) that the function takes.
- For any $x$, we multiply by three and add 4, which is the *relationship*.
- Finally, $f(x)$ or $y$ is the unique result, or the *output*.
The most common name to give a function is, predictably, "$f$", but we can have other names such as "$g$" or "$h$". The choice is yours.
::: callout-important
When reading out loud, we say "\[name of function\] of x equals \[relationship\]. For example, $f(x) = x^2$ is referred to as "f of x equals x squared."
:::
### Vertical line test
::: callout-note
#### Exercise
When graphed, vertical lines cannot touch functions at more than one point. Why?
Which of the following represent functions?
{#fig-vertical-line-test}
:::
## Functions in R
Often we need to create our own functions in R. To build them: we use the keyword `function` alongside the following syntax: `function_name <- function(argumentnames){ operation }`
- `function_name`: the name of the function, that will be stored as an object in the R environment. Make the name concise and memorable!
- `function(argumentnames)`: the inputs of the function.
- `{ operation }`: a set of commands that are run in a predefined order every time we call the function.
For example, we can create a function that multiplies a number by 2:
```{r}
mult_by_two <- function(x){x * 2}
```
```{r}
mult_by_two(x = 5) # we can also omit the argument name (x =)
```
If the function body works for vectors, our custom function will do too:
```{r}
mult_by_two(1:10)
```
We can also automate more complicated tasks such as calculating the area of a circle from its radius:
```{r}
circ_area_r <- function(r){
pi * r ^ 2
}
circ_area_r(r = 3)
```
::: callout-note
#### Exercise
Create a function that calculates the area of a circle *from its diameter*. So `your_function(d = 6)` should yield the same result as the example above. Your code:
:::
Functions can take more than one argument/input. In a silly example, let's generalize our first function:
```{r}
mult_by <- function(x, mult){x * mult}
```
```{r}
mult_by(x = 1:5, mult = 10)
```
```{r}
mult_by(1:5, mult = 10)
```
```{r}
mult_by(1:5, 10)
```
To graph a function, we'll use our friend `ggplot2` and `stat_function()`:
```{r}
library(tidyverse)
```
```{r}
ggplot() +
stat_function(fun = mult_by_two,
xlim = c(-5, 5)) # domain over which we will plot the function
```
User-defined functions have endless possibilities! We encourage you to get creative and try to automate new tasks when possible, especially if they are repetitive.
::: callout-tip
Functions in R can also take non-numeric inputs. For example:
```{r}
say_my_name <- function(my_name){paste("My name is", my_name)}
```
```{r}
say_my_name("Inigo Montoya")
```
:::
## Common types of functions
### Linear functions
$$y=mx+b$$
Linear functions are those whose graph is a straight line (in two dimensions).
- $m$ is the slope, or the rate of change (common interpretation: for every one unit increase in $x$, $y$ increases $m$ units).
- $b$ is the y intercept, or the constant term (the value of $y$ when $x=0$).
Below is a graph of the function $y = 3x + 4$:
```{r}
ggplot() +
stat_function(fun = function(x){3 * x + 4}, # we don't need to create an object
xlim = c(-5, 5))
```
### Quadratic functions
$$y=ax^2 + bx + c$$
Quadratic functions take "U" forms. If $a$ is positive, it is a regular "U" shape. If $a$ is negative, it is an "inverted U" shape.
Note that $x^2$ always returns positive values (or zero).
Below is a graph of the function $y = x^2$:
```{r}
ggplot() +
stat_function(fun = function(x){x ^ 2},
xlim = c(-5, 5))
```
::: callout-note
#### Exercise
Social scientists commonly use linear or quadratic functions as theoretical simplifications of social phenomena. Can you give any examples?
:::
::: callout-note
#### Exercise
Graph the function $y = x^2 + 2x - 10$, i.e., a quadratic function with $a=1$, $b=2$, and $c=-10$.
Next, try switching up these values and the `xlim =` argument. How do they each alter the function (and plot)?
:::
### Cubic functions
$$y=ax^3 + bx^2 + cx +d$$
These lines (generally) have two curves (inflection points).
Below is a graph of the function $y = x^3$:
```{r}
ggplot() +
stat_function(fun = function(x){x ^ 3},
xlim = c(-5, 5))
```
::: callout-note
#### Exercise
We'll briefly introduce [Desmos](https://www.desmos.com/calculator), an online graphing calculator. Use Desmos to graph the following function $y = 1x^3 + 1x^2 + 1x + 1$. What happens when you change the $a$, $b$, $c$, and $d$ parameters?
:::
### Polynomial functions
$$y=ax^n + bx^{n-1} + ... + c$$
These functions have (a maximum of) $n-1$ changes in direction (turning points). They also have (a maximum of) $n$ x-intercepts.
High-order polynomials can be made arbitrarily precise!
Below is a graph of the function $y = \frac{1}{4}x^4 - 5 x^2 + x$.
```{r}
ggplot() +
stat_function(fun = function(x){1/4 * x ^ 4 - 5 * x ^ 2 + x},
xlim = c(-5, 5))
```
### Exponential functions
$$y = ab^{x}$$
Here our input ($x$), is the exponent.
Below is a graph of the function $y = 2^x$:
```{r}
ggplot() +
stat_function(fun = function(x){2 ^ x},
xlim = c(-5, 5))
```
::: callout-note
#### Exercise
Exponential *growth* appears quite frequently social science theories. Which variables can be theorized to have exponential growth over time?
:::
## Logarithms and exponents
### Logarithms
Logarithms are the opposite/inverse of exponents. They ask how many times you must raise the base to get $x$.
So $log_a(b)=x$ is asking "a raised to what power x gives b?" For example, $\log_3(81) = 4$ because $3^4=81$.
::: callout-warning
Logarithms are *undefined* if the base is $\le 0$ (at least in the real numbers).
:::
### Relationships
If, $$ log_ax=b$$ then, $$a^{log_{a}x}=a^b$$ and $$x=a^b$$
### Basic rules
* Change of Base rule: $\dfrac{\log_x n}{\log_x m} = \log_m n$
* Product Rule: $\log_x(ab) = \log_xa + \log_xb$
* Quotient Rule: $\log_x\left(\frac{a}{b}\right) = \log_xa - \log_xb$
* Power Rule: $\log_xa^b = b \log_x a$
* Logarithm of 1: $\log_x 1 = 0$
* Logarithm of the Base: $log_{x}x=1$
* Exponential Identity: $m^{\log_m(a)} = a$
### Natural logarithms
- We most often use natural logarithms for our purposes.
- This means $log_e(x)$, which is usually written as $ln(x)$.
::: callout-important
$e \approx 2.7183$.
:::
- $ln(x)$ and its exponent opposite, $e^x$, have nice properties when we perform calculus.
### Illustration of $e$
Imagine you invest \$1 in a bank and receive 100% interest for one year, and the bank pays you back once a year: $$(1+1)^1= 2$$.
When it pays you twice a year with compound interest:
$$(1+1/2)^2=2.25$$
If it pays you three times a year:
$$(1+1/3)^3=2.37...$$
What will happen when the bank pays you once a month? Once a day?
$$(1+\frac{1}{n})^{n}$$
However, there is limit to what you can get.
$$\lim_{n\to\infty} (1 + \dfrac{1}{n})^n = 2.7183... = e$$
For any interest rate $k$ and number of times the bank pays you $t$: $$\lim_{n\to\infty} (1 + \dfrac{k}{n})^{nt} = e^{kt}$$
> $e$ is important for defining *exponential growth*. Since $ln(e^x) = x$, the natural logarithm helps us turn exponential functions into linear ones.
::: callout-note
## Exercise
Solve the problems below, simplifying as much as you can. $$log_{10}(1000)$$ $$log_2(\dfrac{8}{32})$$ $$10^{log_{10}(300)}$$ $$ln(1)$$ $$ln(e^2)$$ $$ln(5e)$$
:::
### Logarithms in R
By default, R's `log()` function computes natural logarithms:
```{r}
log(100)
```
We can change this behavior with the `base =` argument:
```{r}
log(100, base = 10)
```
We can also plot logarithms. Remember that $ln(x)$ $\forall x<0$ is undefined (at least in the real numbers), and `ggplot2` displays a nice warning letting us know!
```{r}
ggplot() +
stat_function(fun = function(x){log(x)},
xlim = c(-5, 5))
```
```{r}
ggplot() +
stat_function(fun = function(x){log(x)},
xlim = c(1, 100))
```
## Composite functions (functions of functions)
Functions can take other functions as inputs, e.g., $f(g(x))$. This means that the outside function takes the output of the inside function as its input.
Say we have the exterior function $$f(x)=x^2$$
and the interior function $$g(x)=x-3$$.
Then if we want $f(g(x))$, we would subtract 3 from any input, and then square the result or $$f(g(x)) = (x-3)^2$$.
:::callout-warning
We write this as $(x-3)^2$, not $x^2-3$!
:::
R can handle this just fine:
```{r}
f <- function(x){x ^ 2}
g <- function(x){x - 3}
```
```{r}
f(g(5))
```
Here we can also use pipes to make this code more readable (imagine if we were chaining multiple functions...). Remember that pipes can be inserted with the `Cmd/Ctrl + Shift + M` shortcut.
```{r}
# compute g(5), THEN f() of that
g(5) |> f()
```
::: callout-note
#### Exercise
Compute `g(f(5))` using the definitions above. First do it manually, and then check your answer with R.
:::