-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy path3-2_Functions1_practical.qmd
More file actions
144 lines (102 loc) · 1.92 KB
/
Copy path3-2_Functions1_practical.qmd
File metadata and controls
144 lines (102 loc) · 1.92 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
# Functions1: Questions {.unnumbered}
## 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?
:::
::: 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)
```
:::
::: panel-tabset
### Question 3
Do Q2 again but rearrange the arguments.
:::
::: panel-tabset
### Question 4
Do Q2 again using positional matching.
:::
::: panel-tabset
### Question 5
Determine the class of `mean()` using `class()`.
:::
::: panel-tabset
### Question 6
Determine the class of `mean()` using `str()`.
:::
::: panel-tabset
### Question 7
Determine the class of the value output in Q4 using `class()`.
:::
::: panel-tabset
### Question 8
Determine the class of the value output in Q4 using str().
:::
## 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)
```
:::
::: 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))
}
```
:::
::: 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?
:::