-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path9_24_24_classnotes.R
60 lines (60 loc) · 1.53 KB
/
9_24_24_classnotes.R
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
## Code written by the person who made the function f()
f <- function(num) {
hello <- "Hello, world!\n"
for (i in seq_len(num)) {
cat(hello)
}
chars <- nchar(hello) * num
chars
}
## Code written by the user of f()
f()
## Users are forced to specify a value for the argument "num"
f(num = 2)
f(2)
## Create a version of f() with a default value for "num"
## (here we have the default as 1)
f <- function(num = 1) {
hello <- "Hello, world!\n"
for (i in seq_len(num)) {
cat(hello)
}
chars <- nchar(hello) * num
chars
}
## Using f() with no "num" in our global environment
stopifnot(!"num" %in% ls()) ## formally check that "num"
## doesn't exist
f() ## "num" will be created inside of the function f()
## with the default value of 1
f(num = 3) ## Use the code inside f() with num = 3
num <- 4
f() ## Here even though "num" exists on the global
## environment, "num" inside f() uses the default value of 1
## We could have called our argument "number_of_iterations"
## instead of "num"
f <- function(number_of_iterations = 1) {
hello <- "Hello, world!\n"
for (i in seq_len(number_of_iterations)) {
cat(hello)
}
chars <- nchar(hello) * number_of_iterations
chars
}
f("a")
f(0)
f(1)
f <- function(number_of_iterations = 1) {
## Check that the user provided the right type of input
stopifnot(is.numeric(number_of_iterations))
stopifnot(number_of_iterations >= 1)
hello <- "Hello, world!\n"
for (i in seq_len(number_of_iterations)) {
cat(hello)
}
chars <- nchar(hello) * number_of_iterations
chars
}
f("a")
f(0)
f(1)