-
Notifications
You must be signed in to change notification settings - Fork 1
/
functions.qmd
299 lines (201 loc) · 5.96 KB
/
functions.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
---
title: "Figuring out functions"
format: html
engine: knitr
filters:
- webr
---
**Note: You can run selected lines of R code by pressing CTRL-Enter after selecting them.**
# Quick Answers
::: panel-tabset
# How do I make a function in R?
Notes:
- Replace anything starting with `my` with names meaningful to your analysis.
- You can have zero or more arguments(inputs) to your function
- To return more than one object, put them in a list then return the list.
```{webr-r}
myFunction <- function(myArg1, myArg2){
# Do something with myArg1 and myArg2
# and the result of interest in an object
# (e.g. vector, list or data frame)
myResult <- myArg1 * myArg2
# Return the result object
return(myResult)
}
x <- 5
y <- 10
z <- myFunction(x,y)
print(z)
```
:::
# What is a function?
A function is block of R code can be stored in an object, and can then be run using the name of the object. Functions can be given zero or more R objects to use when running the code block.
Running a function is often referred to as "calling the function". E.g. "You can perform linear regression by calling the lm() function."
Examples of common functions in R include `mean()`, `lm()`, and `summary()`.
# Parts of a function
A function has two core parts: its argument list (technically called its *formals*) and its *body*.
- The argument list contains a list of objects (usually data) that will be made available to the function when it is called.
- The body of a function contains the code that the function will run. This is usually one or more R expressions, typically followed by a return() statement.
Here are three examples:
::: panel-tabset
# mySum()
```{webr-r}
# a,b is function's argument list
mySum <- function(a, b){
# the next two lines are the function's body
c <- a + b
return(c)
}
# Usage example:
mySum(4,76)
```
# greeting()
```{webr-r}
# This function has an empty argument list
greeting <- function(){
# The function body contains only the next line. There is no return() statement.
print("Greetings!")
# Note: this function does not return an object or value.
}
# Usage example
greeting()
```
# mean()
```{webr-r}
# This function takes a single argument, x, a numeric vector
runRegression <- function(dataset){
# The body of this function performs linear regression
# and returns the adjusted R-squared value.
fit <- lm(y ~ x, data=dataset)
fit.sum <- fit |> summary()
return(fit.sum$adj.r.squared)
}
# Usage example
myDataframe <- data.frame(x = rnorm(10), y = rnorm(10)) # make a dataframe.
runRegression(myDataframe)
```
:::
# Function Part: Argument list
Arguments are the objects that are provided to a function so that it can perform some action using them. There are several important things to know about these arguments.
* Functions can many arguments, or they can have an empty argument list.
* Function arguments have names.
* Function arguments can have default values.
* Function arguments have a specific order.
## Argument Length
::: panel-tabset
# Zero arguments
```{webr-r}
# This function takes no arguments
getMonths <- function(){
monthNames <- c("January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December")
return(monthNames)
}
# Usage example
getMonths()
```
# One arguments
```{webr-r}
# This function takes a single argument
greetPerson <- function(personName){
message("Hello, ", personName, "!")
# Note: This function does not return anything.
}
# Usage example
person <- "John"
greetPerson(person)
```
# Two arguments
```{webr-r}
# This function takes two arguments
calcBMI <- function(height, weight){
BMI <- weight / height^2
return(BMI)
}
# Usage example
weight <- 65
calcBMI(1.8, weight)
```
:::
## Argument names
There are four important things to understand about the names of function arguments:
* To use a named argument when calling a function, put the argument name, and equals sign "=", and then the object/value.
* Function arguments names lets you rearrange the order of arguments when calling a function.
* Function argument names are not required when calling a function unless you are rearranging the argument order.
* The function arguments in the argument list only exist inside the function.
::: panel-tabset
# Specifying names
```{webr-r}
triple <- function(myNum){
result <- myNum*3
return(result)
}
# Usage Example: No name
x <- 5
triple(x)
# Usage Example: Named argument
x <- 5
triple(myNum = x)
```
# Rearranging order
```{webr-r}
printFullName <- function(firstname, middlename, lastname){
message("Full Name: ", firstname, " ", middlename, " ", lastname)
# This function does not return anything.
}
# Usage Example: Normal order for arguments (no names)
printFullName("Jan", "Igor", "Hanssen")
# Usage Example: Rearranged order for arguments (names required)
printFullName(lastname="Hanssen", firstname="Jan", middlename="Igor")
# Usage Example: Incorrect output (without names)
printFullName("Hanssen", "Jan", "Igor") # The computer is not psychic.
```
# Names not required
```{webr-r}
hoursToMinutes <- function(hours){
return(hours*60)
}
# Usage Example: Without names
hoursToMinutes(2)
# Usage Example: With names
hoursToMinutes(hours = 2)
# Output is the same.
```
# Arguments only within function
```{webr-r}
inchesToMeters <- function(inches){
meters <- inches * 2.54 / 100
return(meters)
}
# Usage Example: Without names
x <- inchesToMeters(60)
# This gives an error, because the meters object only exists inside the function.
print(meters)
```
:::
# Function Part: Body
# Exercise Set 1: Simple functions
Now try turning the following expressions into simple functions:
::: panel-tabset
# Exercise 1.1
```{webr-r}
# Calculate the cube of a number
x <- 3
x*x*x
# Your function
cubeNum <- function(x){
# Put your code here.
}
# Use your function
cubeNum(10)
```
# Solution 1.1
```{webr-r}
# Your function
cubeNum <- function(x){
# Calculate the cube of a number
x*x*x
}
# Use your function
cubeNum(10)
```
:::