-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path01-basic-functions.R
62 lines (54 loc) · 1.62 KB
/
01-basic-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
#Functions have 4 parts:
#a function name (what you call to use the function)
#an argument list (inputs)
# a body (where calculations are made)
#and an return value (output).
#The last line is the return unless overriden with the return command
function_name <- function(input1, input2) {
#THIS IS THE BODY
a <- input1^2
b <- input2^2
sqrt(a + b) #THIS IS THE OUTPUT
}
h <- function_name(3,4) #Yep
function_name(3) #Nope (why not?)
function_name(3, "4") #Nope (why not?)
function_name(3:10, 3:10)
#Some things to notice:
#Running the function lines creates the function in the environment
#Calling the function returns only the last value
#Calling the function without all of the input arguments returns an error
#a and b are created within the function, and don't exist in our environment
#Entering vector inputs gives us vector outputs, no addtl coding needed
#None of the names we used were helpful! This would be better
hyp_of_a_triangle <- function(side_a, side_b) {
sqrt(side_a^2 + side_b^2)
}
hyp(3,4)
#Be careful what you name your functions!
#You can overwrite existing functions in R
mean <- function(side_a, side_b) {
sqrt(side_a^2 + side_b^2)
}
mean(1,2)
rm(mean)
mean(c(1,2)) #Phew
#What if we wanted to return an earlier value rather than the last line?
hyp <- function(side_a, side_b) {
a <- side_a^2
b <- side_b^2
h <- sqrt(a + b)
return(h)
}
hyp(3,4)
#How could we return multiple values?
#Let's write it together
hyp <- function(side_a, side_b) {
a <- side_a^2
b <- side_b^2
h <- sqrt(a + b)
output <- list(a = side_a, b = side_b, h = h)
return(output)
}
res <- hyp(3,4)
res$h