-
Notifications
You must be signed in to change notification settings - Fork 18
/
03 functions.R
92 lines (55 loc) · 1.31 KB
/
03 functions.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
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
# Functions ---------------------------------------------------------------
# Functions are also R objects, just like any other!
sqrt
# So their values (function) can be assigned into new object
shoe <- sqrt
shoe(9)
shoe(81)
shoe(shoe(81))
blahblah <- is.logical
blahblah(FALSE)
blahblah("a")
# We can also make new function!
# sum of two dice (from: "Hands-on programming with R")
two_dice <- function() {
die <- 1:6
dice <- sample(die, 2, replace = TRUE)
sum(dice) # the function will return the last command by default
}
two_dice
two_dice()
# sum of n dice
n_dice <- function(n) {
die <- 1:6
dice <- sample(die, n, replace = TRUE)
sum(dice)
}
n_dice(5)
# default values:
n_dice <- function(n = 2) {
die <- 1:6
dice <- sample(die, n, replace = TRUE)
sum(dice)
}
n_dice()
n_dice(50)
# a new measure of distribution symmetry: mean/median.
symmetry <- function(x) {
return(mean(x) / median(x))
}
a <- c(1, 2, 3, 4, 5, 6, 7, 7, 7, 9, 9, 9, 9, 9)
symmetry(a)
# many inputs:
symmetry <- function(x, top = "mean") {
if (top == "mean") {
return(mean(x) / median(x))
} else if (top == "median") {
return(median(x) / mean(x))
} else {
stop("top can only be 'mean' or 'median'")
}
}
symmetry(a)
symmetry(a, top = "mean")
symmetry(a, top = "median")
symmetry(a, top = "mode")