-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy path3-11_functions_practicals_answers.qmd
484 lines (335 loc) · 8.62 KB
/
3-11_functions_practicals_answers.qmd
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
# Functions: Answers {.unnumbered}
::: callout-warning
Make sure that you try the exercises yourself first before looking at the answers
:::
## Function Arguments
::: panel-tabset
### Question 1
Look at the help file for the function `mean()`.
How many arguments does the function have?
What types of vectors are accepted?
What is the default setting for dealing with NA values?
### Answer
Three arguments (plus further arguments).
Numerical and logical vectors are accepted.
The default setting is to NOT remove NA (missing) values.
:::
::: panel-tabset
### Question 2
Use the function `mean()` to calculate the mean of the following values:
::: callout-note
note the `NA` and use named argument matching
:::
```{r, eval = F}
c(1, 2, NA, 6)
```
### Answer
```{r}
mean(x = c(1, 2, NA, 6), na.rm = TRUE)
```
:::
::: panel-tabset
### Question 3
Do Q2 again but rearrange the arguments.
### Answer
```{r}
mean(na.rm = TRUE, x = c(1, 2, NA, 6))
```
:::
::: panel-tabset
### Question 4
Do Q2 again using positional matching.
### Answer
```{r}
mean(c(1, 2, NA, 6), 0, TRUE)
```
:::
::: panel-tabset
### Question 5
Determine the class of `mean()` using `class()`.
### Answer
```{r}
class(mean)
```
The class is `function`.
:::
::: panel-tabset
### Question 6
Determine the class of `mean()` using `str()`.
### Answer
```{r}
str(mean)
```
The class is `function`.
:::
::: panel-tabset
### Question 7
Determine the class of the value output in Q4 using `class()`.
### Answer
```{r}
class(mean(c(1, 2, NA, 6), 0, TRUE))
```
The class is `numeric`
:::
::: panel-tabset
### Question 8
Determine the class of the value output in Q4 using str().
### Answer
```{r}
str(mean(c(1, 2, NA, 6), 0, TRUE))
```
The `num` means the class is `numeric`.
:::
## Function environment and scoping
::: panel-tabset
### Question 9
For each of the following sets of commands, give the value that will be returned by the last command. Try to answer without using R.
a)
```{r, eval=F}
w <- 5
f <- function(y) {
return(w + y)
}
f(y = 2)
```
b)
```{r, eval=F}
w <- 5
f <- function(y) {
w <- 4
return(w + y)
}
f(y = 2)
```
### Answer
a) This will return 7 because `w` is 5 and we are evaluating the function at `y = 2`
b) This will return 6 because `w` is reassigned as 4 inside the function and we are evaluating the function at `y = 2`.
:::
::: panel-tabset
### Question 10
Among the variables `w`, `d`, and `y`, which are global to `f()` and which are local? What is the value of z when executing `f(w)`
```{r}
w <- 2
f <- function(y) {
d <- 3
h <- function(z) {
return(z + d)
}
return(y * h(y))
}
```
### Answer
The object `w` is global to `f()` while `d` and `y` are local to `f()`.
`z` is 2, because it takes the value of `y` when executing `h(y)` in function `f()`, which takes the value of global variable `w` when executing `f(w)`
:::
::: panel-tabset
### Question 11
Do the following in R:
a) Try:
```{r, eval=F}
myFun1 <- function(a) {
b <- 3
myFun2(a)
}
myFun2 <- function(y) {
return(y + a + b)
}
myFun1(10)
```
What happens?
b) Now try:
```{r, eval=F}
a <- 1
b <- 2
myFun1(10)
```
What happens?
### Answer
a) We get an error message because `a` and `b` are local to `myFun1` so the function `myFun2` can't find them in the global environment.
b) We get get the value 13 because the values `a` and `b` are global so `myFun2` can find them and use them in its commands.
:::
## if(), else, and ifelse() and Vectorization
::: panel-tabset
### Question 12
Write a function called 'evenOrOdd' involving `if` and `else` that takes an argument `x` and returns "Even" or "Odd" depending on whether or not `x` is divisible by 2. (Do not use the ifelse() function).
### Anwser
```{r}
evenOrOdd <- function(x) {
if(x %% 2 == 0) {
return("Even")
} else {
return("Odd")
}
}
```
:::
::: panel-tabset
### Question 13
Is your function 'evenOrOdd' vectorized? Check by passing it the vector:
```{r}
w <- c(3, 6, 6, 4, 7, 9, 11, 6)
```
### Answer
```{r,error=T}
evenOrOdd(w)
```
An error is given, because x in `if(x %% 2 == 0)` is longer than 1.
:::
::: panel-tabset
### Question 14
Another way to determine if each element of a vector is even or odd is to use the `ifelse()` function, which serves as a vectorized version `if` and `else`. Use `ifelse()` to obtain "Even" or "Odd" for each element of `w`.
### Answer
```{r}
ifelse(w %% 2 == 0, "Even", "Odd")
```
:::
## Terminating a function with returns, errors, and warnings
The functions `warning()` and `stop()` are used to print a warning message and to stop the execution of the function call and print an error message. For example:
```{r}
noNegMean <- function(x) {
if(all(x < 0)) {
stop("All values in x are negative")
}
if(any(x < 0)) {
x[x < 0] <- 0
warning("Negative values in x replaced by zero")
}
return(mean(x))
}
```
::: panel-tabset
### Question 15
Copy the above code and then pass `noNegMean()` a vector containing some negative and some positive values. What happens?
### Answer
```{r}
noNegMean(c(-1,0,1))
```
We get the warning message and it returned 0.3333, which is the average of `c(0, 0, 1)`.
:::
::: panel-tabset
### Question 16
What happens when you pass `noNegMean()` a vector containing all negative values?
### Answer
```{r,error=T}
noNegMean(c(-1,-1,-1))
```
We get the error message and nothing is returned.
:::
::: panel-tabset
### Question 17
Write a function `ratio()` that takes two arguments, `x` and `y`, and attempts to compute the ratio `x/y`.
If both `x == 0 & y == 0`, the function should stop and print an error message about dividing 0 by 0.
If `y == 0` (but not x), the function should print a warning message about dividing by 0, and then return `x/y` (which will be `Inf`).
In all other cases, it should return `x/y`.
Test your `ratio()` function first using two nonzero values for `x` and `y`, then using a nonzero `x` but `y = 0`, and finally using `x = 0` and `y = 0`.
### Answer
```{r}
ratio <- function(x,y) {
if(x == 0 & y == 0) {
stop("Cannot divide zero by zero.")
}
if(y == 0) {
warning("Cannot divide by zero.")
}
ratio <- x/y
return(ratio)
}
```
```{r, error=T}
ratio(2,3)
ratio(0,0)
ratio(1,0)
```
:::
## looping using for() loops and the apply functions
::: panel-tabset
### Question 18
Copy this is a function to determine if a number is a prime number:
```{r}
isPrime <- function(num){
if (num == 2) {
return(TRUE)
}
if(num > 1) {
for(i in 2:(num-1)) {
if ((num %% i) == 0) {
return(FALSE)
}
}
} else {
return(FALSE)
}
return(TRUE)
}
```
Copy this matrix for which we would like to check if a number is a prime number:
```{r}
mat <- matrix(1:100, nrow=10)
```
Use the `apply()` function to calculate the prime number for each number in the matrix.
What numbers from 1 until 100 are prime numbers?
### Answer
```{r}
apply(mat, c(1,2), isPrime)
```
```{r}
mat[apply(mat, c(1,2), isPrime)]
```
:::
::: panel-tabset
### Question 19
Copy the following command to create a list containing two generations of the famous Kennedy family:
```{r}
Kennedys <- list(
JosephJr = character(0),
John = c("Caroline", "JohnJr", "Patrick"),
Rosemary = character(0),
Kathleen = character(0),
Eunice = c("RobertIII", "Maria", "Timothy", "Mark", "Anthony"),
Patricia = c("Christopher", "Sydney", "Victoria", "Robin"),
Robert = c("Kathleen", "JosephII", "RobertJr", "David",
"MaryC", "Michael", "MaryK", "Christopher",
"Matthew", "Douglas", "Rory"),
Jean = c("Stephen", "William", "Amanda", "Kym"),
Edward = c("Kara", "EdwardJr", "Patrick")
)
```
Use a `for()` loop to loop over the list of the first generation of Kennedys, keeping track of how many children each one has in a vector.
### Answer
```{r}
children <- NULL
for(i in Kennedys){
children <- c(children, length(i))
}
children
```
:::
::: panel-tabset
### Question 20
Now, using the `lapply()` function, loop over the list of the first generation of Kennedys and keep track of how many children each Kennedy has. What is the class of the output?
### Answer
```{r}
result <- lapply(Kennedys, length)
result
class(result)
```
:::
::: panel-tabset
### Question 21
Answer Question 20 again using the `sapply()` function. What is the class of the output?
### Answer
```{r}
result <- sapply(Kennedys, length)
result
class(result)
```
:::
::: panel-tabset
### Question 22
Load the "diamonds" dataset from the ggplot2 package by running `library(gglot2)` and calculate the average price of diamonds by color and clarity using the `tapply()` function.
### Answer
```{r}
library(ggplot2)
tapply(diamonds$price, list(diamonds$color, diamonds$clarity), mean)
```
:::