-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsolutions.qmd
More file actions
827 lines (634 loc) · 21 KB
/
solutions.qmd
File metadata and controls
827 lines (634 loc) · 21 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
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
# Solutions to exercises {.unnumbered}
## 1. Intro to R
> **Exercise**
>
> Create your own code block below and run a math operation.
```{r}
pi * 2
```
> **Exercise**
>
> Examine the help file of the `log()` function. How can we compute the the base-10 logarithm of my_object? Your code:
```{r}
#| code-fold: true
#| message: false
# setup: these steps were executed before the exercise
my_object <- 10
```
1) Examine the `log()` function.
```{r}
#| eval: false
?log
```
2) Compute the base-10 logarithm of `my_object`.
```{r}
log(my_object, base = 10)
```
```{r}
# alternative:
log10(my_object)
```
> **Exercise**
>
> Obtain the maximum value of water content per 100g in the data. Your code:
```{r}
#| code-fold: true
#| message: false
#| results: hide
# setup: these steps were executed before the exercise
my_character_vector <- c("Apple", "Orange", "Watermelon", "Banana")
my_data_frame <- data.frame(fruit = my_character_vector,
calories_per_100g = c(52, 47, 30, 89),
water_per_100g = c(85.6, 86.8, 91.4, 74.9))
my_data_frame
```
```{r}
max(my_data_frame$water_per_100g)
```
## 2. Tidy data analysis I {.unnumbered}
```{r}
#| code-fold: true
#| message: false
#| results: hide
# setup: these steps were executed before the exercises
library(tidyverse)
trump_scores <- read_csv("data/trump_scores_538.csv")
```
> **Exercise**
>
> Select the variables `last_name`, `party`, `num_votes`, and `agree` from the data frame. Your code:
```{r}
trump_scores |>
select(last_name, party, num_votes, agree)
```
```{r}
# alternative
trump_scores |>
select(last_name, party:agree)
```
> **Exercise**
>
> 1. Add a new column to the data frame, called `diff_agree`, which subtracts `agree` and `agree_pred`. How would you create `abs_diff_agree`, defined as the absolute value of `diff_agree`? Your code:
>
> 2. Filter the data frame to only get senators for which we have information on fewer than (or equal to) five votes. Your code:
>
> 3. Filter the data frame to only get Democrats who agreed with Trump in at least 30% of votes. Your code:
1) Add a new column to the data frame, called `diff_agree`, which subtracts `agree` and `agree_pred`. How would you create `abs_diff_agree`, defined as the absolute value of `diff_agree`? Your code:
```{r}
trump_scores |>
mutate(diff_agree = agree - agree_pred) |>
select(last_name, matches("agree")) # just for clarity
```
```{r}
trump_scores |>
mutate(abs_diff_agree = abs(agree - agree_pred)) |>
select(last_name, matches("agree")) # just for clarity
```
2) Filter the data frame to only get senators for which we have information on fewer than (or equal to) five votes. Your code:
```{r}
trump_scores |>
filter(num_votes <= 5)
```
3) Filter the data frame to only get Democrats who agreed with Trump in at least 30% of votes. Your code:
```{r}
trump_scores |>
filter(party == "D" & agree >= 0.3)
```
> **Exercise**
>
> Arrange the data by `diff_pred`, the difference between agreement and predicted agreement with Trump. (You should have code on how to create this variable from the last exercise). Your code:
```{r}
trump_scores |>
mutate(diff_agree = agree - agree_pred) |>
arrange(diff_agree)
```
> **Exercise**
>
> Obtain the maximum absolute difference in agreement with Trump (the `abs_diff_agree` variable from before) for each party.
```{r}
trump_scores |>
mutate(abs_diff_agree = abs(agree - agree_pred)) |>
summarize(max_abs_diff = max(abs_diff_agree),
.by = party)
```
> **Exercise**
>
> Draw a column plot with the agreement with Trump of Bernie Sanders and Ted Cruz. What happens if you use `last_name` as the `y` aesthetic mapping and `agree` in the `x` aesthetic mapping? Your code:
```{r}
#| code-fold: true
#| message: false
#| results: hide
# setup: this step was executed before the exercise
trump_scores_ss <- trump_scores |>
filter(num_votes >= 10)
```
```{r}
ggplot(trump_scores_ss |> filter(last_name %in% c("Cruz", "Sanders")),
aes(y = last_name, x = agree)) +
geom_col()
```
```{r}
# alternative
ggplot(trump_scores_ss |> filter(last_name == "Cruz" | last_name == "Sanders"),
aes(y = last_name, x = agree)) +
geom_col()
```
## 3. Matrices {.unnumbered}
> **Exercise**
>
> Get the product of the first three elements of vector $d$. Write the notation by hand and use R to obtain the number.
>
> $$\overrightarrow d = \begin{bmatrix}
> 12 & 7 & -2 & 3 & 1
> \end{bmatrix}$$
```{r}
#| code-fold: true
#| message: false
# setup: these steps were executed before the exercise
vector_d <- c(12, 7, -2, 3, -1)
```
$$\prod_{i=1}^3 d_i = 12 \cdot 7 \cdot (-2) = -168$$
```{r}
prod(vector_d[1:3])
```
> **Exercise**
>
> 1) Calculate $A + B$ $$A= \begin{bmatrix}
> 1 & 0 \\
> -2 & -1
> \end{bmatrix}$$
>
> $$B = \begin{bmatrix}
> 5 & 1 \\
> 2 & -1
> \end{bmatrix}$$\
>
> 2) Calculate $A - B$ $$A= \begin{bmatrix}
> 6 & -2 & 8 & 12 \\
> 4 & 42 & 8 & -6
> \end{bmatrix}$$ $$B = \begin{bmatrix}
> 18 & 42 & 3 & 7 \\
> 0 & -42 & 15 & 4
> \end{bmatrix}$$
```{r}
A1 <- matrix(c(1,-2,0,-1), nrow = 2)
B1 <- matrix(c(5,2,1,-1), nrow = 2)
A1 + B1
```
```{r}
A2 <- matrix(c(6,4,-2,42,8,8,12,-6), nrow = 2)
B2 <- matrix(c(18,0,42,-42,3,15,7,4), nrow = 2)
A2 - B2
```
> **Exercise**
>
> Calculate $2\times A$ and $-3 \times B$. Again, do one by hand and the other one using R. $$A= \begin{bmatrix}
> 1 & 4 & 8 \\
> 0 & -1 & 3
> \end{bmatrix}$$ $$ B = \begin{bmatrix}
> -15 & 1 & 5 \\
> 2 & -42 & 0 \\
> 7 & 1 & 6
> \end{bmatrix}$$
```{r}
A3 <- matrix(c(1,0,4,-1,8,3), nrow = 2)
2 * A3
```
```{r}
B3 <- matrix(c(-15,2,7,1,-42,1,5,0,6), nrow = 3)
-3 * B3
```
## 4. Tidy data analysis II {.unnumbered}
> **Exercise**
>
> 1. Create a dummy variable, `d_large_pop`, for whether the country-year has a population of more than 1 million. Then compute its mean. Your code:
> 2. Which countries are recorded as "Never colonized"? Change their values to other reasonable codings and compute a tabulation with `count()`. Your code:
```{r}
#| code-fold: true
#| message: false
# setup: these steps were executed before the exercise
library(tidyverse)
qog_csv <- read_csv("data/sample_qog_bas_ts_jan23.csv")
qog <- qog_csv
```
1. Create the dummy variable `d_large_pop`.
```{r}
qog |>
mutate(d_large_pop = if_else(wdi_pop >= 1000000, 1, 0)) |>
count(d_large_pop) # to check if it went well
```
2. Change the coding of "Never colonized" countries to something else, and compute a tabulation with `count()`.
```{r}
qog |>
filter(ht_colonial == "Never colonized") |>
count(cname)
```
```{r}
qog |>
mutate(ht_colonial_recoded = case_when(
cname == "Canada" ~ "French/British",
cname == "United States" ~ "British",
.default = ht_colonial
)) |>
count(ht_colonial_recoded)
```
> **Exercise**
>
> Calculate the median value of the corruption variable for each region (i.e., perform a grouped summary). Your code:
```{r}
qog |>
summarize(med_corr = median(vdem_corr, na.rm = T), .by = region)
```
> **Exercise**
>
> Convert back `gdp_long` to a wide format using `pivot_wider()`. Check out the help file using `?pivot_wider`. Your code:
```{r}
#| code-fold: true
#| message: false
# setup: these steps were executed before the exercise
library(readxl)
gdp <- read_excel("data/wdi_gdp_ppp.xlsx")
gdp_long <- gdp |>
pivot_longer(cols = -c(country_name, country_code),
names_to = "year",
values_to = "wdi_gdp_ppp",
names_transform = as.integer)
```
```{r}
gdp_long |>
pivot_wider(id_cols = c(country_name, country_code), # can omit in this case too
values_from = wdi_gdp_ppp,
names_from = year)
```
> **Exercise**
>
> There is a dataset on country's CO2 emissions, again from the World Bank ([2023](https://data.worldbank.org/)), in "data/wdi_co2.csv". Load the dataset into R and add a new variable with its information, `wdi_co2`, to our `qog_plus` data frame. Finally, compute the average values of CO2 emissions *per capita*, by country. Tip: this exercise requires you to do many steps---plan ahead before you start coding! Your code:
```{r}
#| code-fold: true
#| message: false
# setup: these steps were executed before the exercise
library(tidyverse)
qog <- read_csv("data/sample_qog_bas_ts_jan23.csv")
gdp <- readxl::read_excel("data/wdi_gdp_ppp.xlsx")
gdp_long <- gdp |>
pivot_longer(cols = -c(country_name, country_code),
names_to = "year",
values_to = "wdi_gdp_ppp",
names_transform = as.integer)
qog_plus <- left_join(qog,
gdp_long,
by = c("ccodealp" = "country_code",
"year"))
```
1) Load data (notice the .csv format):
```{r}
emissions <- read_csv("data/wdi_co2.csv")
```
2) Pivot data to long, creating the "wdi_co2" variable:
```{r}
emissions_long <- emissions |>
pivot_longer(cols = -c(country_name, country_code),
names_to = "year",
values_to = "wdi_co2",
names_transform = as.integer)
```
3) Merge-in information to our existing `qog_plus` data frame:
```{r}
qog_plus2 <- left_join(qog_plus,
emissions_long,
by = c("ccodealp" = "country_code",
"year"))
```
4) Create column for emissions *per capita* (here we do per 1,000 people).
5) Summarize information to get mean values at the country level (remember that `na.rm = T` is always a conscious decision):
```{r}
qog_plus2 |>
mutate(emissions_pc = 1000 * wdi_co2 / wdi_pop) |>
summarize(emissions_pc_country = mean(emissions_pc, na.rm = T),
.by = cname)
```
> **Exercise**
>
> Draw a scatterplot with time in the x-axis and democracy scores in the y-axis. Your code:
```{r}
ggplot(qog_plus2) + aes(year, vdem_polyarchy) + geom_point()
```
> **Exercise**
>
> Using your merged dataset from the previous section, plot the trajectories of C02 per capita emissions for the US and Haiti. Use adequate scales.
```{r}
ggplot(qog_plus2 |> filter(cname %in% c("Haiti", "United States")),
aes(x = year, y = 1000 * wdi_co2 / wdi_pop)) +
geom_line() +
facet_wrap(~cname, scales = "free_y") +
labs(x = "Year", y = "CO2 Emissions Per Capita",
title = "CO2 Emissions Per Capita in Haiti and the United States",
caption = "Source: World Development Indicators (World Bank, 2023) in QOG dataset.")
```
## 5. Functions {.unnumbered}
> **Exercise** When graphed, vertical lines cannot touch functions at more than one point. Why? Which of the following represent functions?
>
> {#fig-vertical-line-test}
A) Function ✅
B) Function ✅
C) NOT a function 🚫
D) Function ✅
E) Function ✅
F) NOT a function 🚫
G) Function ✅
H) NOT a function 🚫
> **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:
```{r}
#| code-fold: true
#| message: false
# setup: these steps were executed before the exercise
circ_area_r <- function(r){
pi * r ^ 2
}
circ_area_r(r = 3)
```
```{r}
circ_area_d <- function(d){
pi * (d/2) ^ 2
}
circ_area_d(d = 6)
```
> **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)?
```{r}
#| code-fold: true
#| message: false
# setup: these steps were executed before the exercise
library(ggplot2)
```
1) Graph $y = x^2 + 2x - 10$.
```{r}
ggplot() +
stat_function(fun = function(x){x^2 + 2*x - 10},
xlim = c(-5, 5))
```
2) Switch up the values and the `xlim =` argument.
```{r}
ggplot() +
stat_function(fun = function(x){-3*x^2 - 6*x + 9},
xlim = c(-10, 10))
```
> **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?
(we'll show how to do this in R here, but you could use Desmos)
1) Graph $y = 1x^3 + 1x^2 + 1x + 1$.
```{r}
ggplot() +
stat_function(fun = function(x){x^3 + x^2 + x + 1},
xlim = c(-10, 10))
```
2) Switch up the values.
```{r}
ggplot() +
stat_function(fun = function(x){-2*x^3 + 4*x^2 + 8*x + 16},
xlim = c(-10, 10))
```
> **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)$$
```{r}
log10(1000)
```
```{r}
log2(8/32)
```
```{r}
10^(log10(300))
```
```{r}
log(1)
```
```{r}
log(exp(2))
```
```{r}
log(5*exp(1))
```
> **Exercise**
>
> Compute `g(f(5))` using the definitions above. First do it manually, and then check your answer with R.
```{r}
#| code-fold: true
#| message: false
# setup: these steps were executed before the exercise
f <- function(x){x ^ 2}
g <- function(x){x - 3}
```
$$f(5) = 5^2 = 25$$ $$g(25) = 25 - 3 = 22$$
```{r}
g(f(5)) # no pipeline approach
f(5) |> g() # pipeline approach
```
## 6. Calculus {.unnumbered}
> **Exercise**
>
> 1) Use the slope formula to calculate the rate of change between 5 and 6.
> 2) Use the slope formula to calculate the rate of change between 5 and 5.5.
> 3) Use the slope formula to calculate the rate of change between 5 and 5.1.
```{r}
(6^2 - 5^2) / (6 - 5)
```
```{r}
(5.5^2 - 5^2) / (5.5 - 5)
```
```{r}
(5.1^2 - 5^2) / (5.1 - 5)
```
> **Exercise**
>
> Use the differentiation rules we have covered so far to calculate the derivatives of $y$ with respect to $x$ of the following functions:
>
> 1. $y = 2x^2 + 10$
> 2. $y = 5x^4 - \frac{2}{3}x^3$
> 3. $y = 9 \sqrt x$
> 4. $y = \frac{4}{x^2}$
> 5. $y = ax^3 + b$, where $a$ and $b$ are constants.
> 6. $y = \frac{2w}{5}$
1) $4x$ (sum rule, constant rule, coefficient rule, power rule)
2) $20x^3-2x^2$ (sum rule, coefficient rule, power rule)
3) $\frac{-9}{2\sqrt x}$ (power rule)
4) $-\frac{8}{x^3}$ (coefficient rule, power rule)
5) $3ax^2$ (sum rule, constant rule, coefficient rule, power rule)
6) $0$ (constant rule)
> **Exercise**
>
> Compute the following:
>
> 1. $\frac{d}{dx}(10e^x)$
> 2. $\frac{d}{dx}(ln(x) - \frac{e^2}{3})$
1) $10e^x$ (coefficient rule, exponent rule)
2) $\frac{1}{x}$ (difference rule, constant rule, logarithm rule)
> **Exercise**
>
> Use the differentiation rules we have covered so far to calculate the derivatives of $y$ with respect to $x$ of the following functions:
>
> 1. $x^3 \cdot x$
> 2. $e^x \cdot x^2$
> 3. $(3x^4-8)^2$
1) $4x^3$ (power rule)
2) $e^x x^2 + 2xe^x$ (product rule, exponent rule, power rule)
3) $24x^3(3x^4-8)$ (chain rule, difference rule, constant rule, power rule)
> **Exercise**
>
> Take the partial derivative with respect to $x$ and with respect to $z$ of the following functions. What would the notation for each look like?
>
> 1. $y = 3xz - x$
> 2. $x^3+z^3+x^4z^4$
> 3. $e^{xz}$
1)
$\frac{\delta}{\delta x}(3xz - x) = 3z - 1$ (difference rule, coefficient rule, power rule)
$\frac{\delta}{\delta z}(3xz - x) = 3x$ (difference rule, constant rule, coefficient rule)
2)
$\frac{\delta}{\delta x}(x^3+z^3+x^4z^4) = 4x^3z^4+3x^2$ (add rule, coefficient rule, power rule)
$\frac{\delta}{\delta z}(x^3+z^3+x^4z^4) = 4x^4z^3+3z^2$ (add rule, coefficient rule, power rule)
3)
$\frac{\delta}{\delta x}(e^{xz}) = e^{xz}z$ (chain rule, exponent rule, coefficient rule)
$\frac{\delta}{\delta z}(e^{xz}) = e^{xz}x$ (chain rule, exponent rule, coefficient rule)
> **Exercise**
>
> Identify the global extrema of the function $\displaystyle \frac{x^3}{3} - \frac{3}{2}x^2 -10x$ in the interval $[-6, 6]$.
1) Take the first derivative
$(\frac{x^3}{3} - \frac{3}{2}x^2 -10x)' = x^2 - 3x - 10$ (sum rule, coefficient rule, power rule)
2) Set the derivative equal to zero and obtain its roots (F.O.C)
$ x^2 - 3x - 10 = (x-5)(x+2)$
$(x-5)(x+2) = 0$
$x^*_1 = 5,\, x^*_2=-2$
3) Calculate the second derivative and substitute the roots (S.O.C.)
$(x^2 - 3x - 10)' = 2x -3$
(i) $2x^*_1-3 = 2\cdot5-3 = 7$ (since it is positive, this is a minimum)
(ii) $2x^*_2-3 = 2\cdot(-2)-3 = -7$ (since it is negative, this is a maximum)
4) Adjudicate between these critical points or the bounds.
Minimum critical point: $f(5) = \frac{(5)^3}{3} - \frac{3}{2}(5)^2 -10 \cdot (5) = −45.8\overline{3}$.
Maximum critical point: $f(-2) = \frac{(-2)^3}{3} - \frac{3}{2}(-2)^2 -10 \cdot (-2) = 11.\overline{3}$.
Lower bound: $f(-6) = \frac{(-6)^3}{3} - \frac{3}{2}(-6)^2 -10 \cdot (-6) = −66$
Upper bound: $f(6) = \frac{(-6)^3}{3} - \frac{3}{2}(-6)^2 -10 \cdot (-6) = −42$
So we conclude that, for the $[-6, 6]$ interval, the global minimum is at the lower bound ($x=-6$) and the global maximum is at the critical point at $x=-2$.
> **Exercise**
>
> Solve the following indefinite integrals:
>
> 1. $\int x^2 \, dx$
> 2. $\int 3x^2\, dx$
> 3. $\int x\, dx$
> 4. $\int (3x^2 + 2x - 7\,)dx$
> 5. $\int \dfrac{2}{x}\,dx$
1. $\frac{x^3}{3} + C$ (power rule)
2. $x^3 + C$ (coefficient rule, power rule)
3. $\frac{x^2}{2} + C$ (power rule)
4. $x^3 + x^2 - 7x + C$ (sum/difference rule, coefficient rule, power rule)
5. $2 ln(x) + C$ (coefficient rule, reciprocal rule)
> And solve the following definite integrals:
>
> 1. $\displaystyle\int_{1}^{7} x^2 \, dx$
> 2. $\displaystyle\int_{1}^{10} 3x^2 \, dx$
> 3. $\displaystyle\int_7^7 x\, dx$
> 4. $\displaystyle\int_{1}^{5} 3x^2 + 2x - 7\,dx$
> 5. $\int_{1}^{e} \dfrac{2}{x}\,dx$
In the following, FTC stands for the Fundamental Theorem of Calculus
1. $114$ (substitute from previous answer, FTC)
2. $999$ (substitute from previous answer, FTC)
3. $0$ (there is no area between 7 and 7)
4. $120$ (substitute from previous answer, FTC)
5. $2$ (substitute from previous answer, FTC)
## 7. Probability, statistics, and simulations {.unnumbered}
> **Exercise**
>
> Compute the probability of seeing between 1 and 10 voters of the candidate in a sample of 100 people.
```{r}
pbinom(q = 10, size = 100, prob = 0.02) -
dbinom(x = 0, size = 100, prob = 0.02)
```
> **Exercise**
>
> Evaluate the CDF of $Y \sim U(-2, 2)$ at point $y = 1$. Use the formula and `punif()`.
$$A = F(1) = P(Y\leq 1) = 3 \cdot(1/4) = 0.75$$
```{r}
punif(q = 1, min = -2, max = 2)
```
> **Exercise**
>
> What is the probability of obtaining a value above 1.96 or below -1.96 in a standard normal probability distribution? Hint: use the `pnorm()` function.
```{r}
pnorm(-1.96) + (1 - pnorm(1.96))
```
> **Exercise**
>
> Compute and plot `my_rnorm`, a vector with one million draws from a Normal distribution $Z$ with mean equal to zero and standard deviation equal to one ($Z\sim N(0,1)$). You can recycle code from what we did for the uniform distribution!
```{r}
set.seed(1) # set a seed
my_rnorm <- rnorm(n = 1000000)
ggplot(data.frame(my_rnorm), aes(x = my_rnorm)) +
geom_histogram(binwidth = 0.25, boundary = 0, closed = "right") +
scale_x_continuous(breaks = seq(-5, 5, 1), limits = c(-5, 5))
```
## 8. Text analysis {.unnumbered}
> **Exercise**
>
> What score (out of 10) would you give Barbie or Oppenheimer? Write your score in one sentence (e.g., I would give Barbie seven of ten stars.) If you have not seen either, write a sentence about which you would like to see more.
>
> Store that text as a string (`string3`) and combine it with our existing `cat_string` to produce a new concatenated string called `cat_string2`. Finally, count the total number of characters within `cat_string2`. Your code:
```{r}
#| code-fold: true
#| message: false
# setup: these steps were executed before the exercise
library(stringr)
my_string <- "I know people who have seen the Barbie movie 2, 3, even 4 times!"
my_string2 <- "I wonder if they have seen Oppenheimer, too."
cat_string <- str_c(my_string, my_string2, sep = " ")
```
```{r}
string3 <- "I would give Barbie 7 out of 10 stars."
string3
cat_string2 <- str_c(cat_string, string3, sep = " ")
cat_string2
str_length(cat_string2)
```
> **Exercise**
>
> Look up the lyrics to your favorite song at the moment (no guilty pleasures here!). Then, follow the process described above to count the words: store the text as a string, convert to a tibble, tokenize, and count.
>
> When you are done counting, create a visualization for the chorus using the `ggplot` code above. Your code:
1. Store the text as a string.
```{r}
library(tidytext)
dummy <- c("I been goin' dummy (Huh)",
"I been goin' dummy (Goin' dummy)",
"I been goin' dummy (Goin' dummy)",
"I been goin' dummy (Goin' dummy)",
"I been goin' dummy (Yeah)",
"I been goin' dummy (Goin' dummy)",
"I been goin' dummy (Goin' dummy)",
"I been goin' dummy",
"Dumbass, I been goin' dummy")
```
2. Convert to a tibble.
```{r}
dummy_df <- tibble(line = 1:9, text = dummy)
dummy_df
```
3. Tokenize.
```{r}
dummy_tok <- unnest_tokens(dummy_df, word, text)
```
4. Count.
```{r}
dummy_tok |>
count(word, sort = TRUE)
```
5. Visualize.
```{r}
dummy_tok |>
count(word, sort = TRUE) |>
mutate(word = reorder(word, n)) |>
ggplot(aes(n, word)) +
geom_col()
```