forked from harris-coding-lab/harris-coding-lab.github.io
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path06_functions.R
116 lines (85 loc) · 2.35 KB
/
06_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
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
# Example from last time
mean(rnorm(1))
mean(rnorm(2))
mean(rnorm(3))
# For loop for iteration
sample_sizes <- 1:30
means <- numeric(length(sample_sizes))
for (i in seq_along(sample_sizes)) {
means[i] = mean(rnorm(i))
}
means
# Function for iteration
calculate_sample_mean <- function(sample_size) {
sample_mean <- mean(rnorm(sample_size))
sample_mean
}
calculate_sample_mean(1)
# Apply the function
sapply(1:30, calculate_sample_mean)
print("Number 1!")
print("Number 2!")
print("Number 3!")
# and so on...
print("Number 10!")
# Write a function to shout numbers
shout_number <- function(number) {
paste0("Number ", number, "!")
}
shout_number(1)
numbers <- 1:10
sapply(numbers, shout_number)
numbers <- 1:10
lapply(numbers, shout_number)
# Write another function to calculate sample means
calculate_sample_mean <- function(sample_size) {
sample_mean <- mean(rnorm(sample_size))
sample_mean
}
calculate_sample_mean(1)
sapply(1:30, calculate_sample_mean)
# Add arguments
calculate_sample_mean <- function(sample_size,
sample_mean = 0,
sample_sd = 1) {
sample_mean <- mean(rnorm(sample_size,
mean = sample_mean,
sd = sample_sd))
sample_mean
}
# Call function with out-of-order arguments
calculate_sample_mean(10, sample_mean = 6, sample_sd = 2)
calculate_sample_mean(sample_sd = 2, sample_size = 9)
# This won't work
# calculate_sample_mean(sample_mean = 5)
# Functions in functions - wow
calculate_sample_mean <- function(sample_size,
sample_mean = 0,
sample_sd = 1,
dist_type = rnorm) {
sample_mean <- mean(dist_type(sample_size,
mean = sample_mean,
sd = sample_sd))
sample_mean
}
# Test it out
calculate_sample_mean(sample_size = 10,
sample_mean = 0,
sample_sd = 1)
calculate_sample_mean(sample_size = 10,
sample_mean = 0,
sample_sd = 1,
dist_type = pnorm)
# Probability distributions
dnorm(0)
dnorm(1)
dnorm(-1)
pnorm(0)
pnorm(1)
pnorm(-1)
qnorm(c(0.05, 0.95))
qnorm(c(0.025, 0.975))
pnorm(qnorm(c(0.025, 0.975)))
rnorm(1)
rnorm(5)
rnorm(30)