-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathfunctions.qmd
More file actions
219 lines (148 loc) · 3.13 KB
/
functions.qmd
File metadata and controls
219 lines (148 loc) · 3.13 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
# Functions
Functions are reusable blocks of code designed to perform a specific task.
Writing functions improves clarity, efficiency, and reproducibility.
## Objectives
- Define and use built-in functions
- Write custom functions
- Return single and multiple values
- Use default arguments
- Create nested functions
- Validate arguments using `stopifnot()`
- Understand basic error handling
## Built-In Functions
R provides many built-in functions for analysis, including:
- `mean()`
- `min()`
- `max()`
- `summary()`
- `quantile()`
### Example: mean()
```{r}
mean(1:5)
```
Handling missing values:
```{r}
v <- c(2, NA, 4, NaN, 6)
mean(v) # returns NA
mean(v, na.rm = TRUE) # removes missing values
```
To use functions from packages:
```r
library(dplyr)
# Example of package function
dplyr::select
```
## Custom Functions
You create a function using `function()`.
### Basic Syntax
```r
f <- function(arg1, arg2, arg3, ...){
# code
}
```
### Example: One Argument
```{r}
squareroot <- function(a){
a^0.5
}
squareroot(49)
```
### Example: Two Arguments
```{r}
Addtwo <- function(a, b){
a + b
}
Addtwo(1, 2)
```
### Returning Values
R automatically returns the last evaluated expression, but `return()` makes it explicit.
```{r}
F2C <- function(temp) {
c <- (temp - 32) * (5 / 9)
return(c)
}
F2C(100)
```
### Returning Multiple Values
Use a list to return multiple outputs.
```{r}
sqsum <- function(a){
sq <- a^0.5
sumsq <- a + sq
output <- list(sq = sq, sumsq = sumsq)
return(output)
}
sqsum(49)
```
## Default Arguments
You can assign default values to arguments.
```{r}
power <- function(x, exponent = 2){
x^exponent
}
power(3) # uses default exponent = 2
power(3, 3) # overrides default
```
Default arguments make functions more flexible.
## Nested Functions
Nested functions combine multiple operations inside one expression.
Example using `mtcars`:
Goal: Compute the mean `mpg` for cars with 4 cylinders.
Step-by-step approach:
```{r}
data(mtcars)
ind1 <- mtcars$cyl == 4
ind2 <- mtcars$mpg[ind1]
mean(ind2)
```
Nested version:
```{r}
mean(mtcars$mpg[mtcars$cyl == 4])
```
You can also define functions inside functions:
```{r}
outer_function <- function(x){
inner_function <- function(y){
y^2
}
inner_function(x) + 1
}
outer_function(3)
```
## Error Handling
Functions should check inputs to avoid incorrect results.
### Using `stopifnot()`
```{r}
safe_sqrt <- function(x){
stopifnot(x >= 0)
sqrt(x)
}
safe_sqrt(9)
```
If the condition fails, R stops execution.
### Using `stop()`
```{r}
safe_divide <- function(a, b){
if(b == 0){
stop("Division by zero is not allowed.")
}
a / b
}
```
### Using `warning()`
```{r}
check_positive <- function(x){
if(x < 0){
warning("Negative value detected.")
}
x
}
```
## Key Points
- Functions improve efficiency and readability
- Built-in functions cover many common tasks
- Custom functions use `function()`
- Use default arguments for flexibility
- Return multiple values using lists
- Nested functions simplify complex operations
- Validate inputs using `stopifnot()` or `stop()`