Writing custom functions is a great way to encapsulate code that you want to re-use
A function has one way in and one way out
example <- function() {
## do something useful here
return()
}
example()
Writing custom functions is a great way to encapsulate code that you want to re-use
A function has one way in and one way out
example <- function() {
## do something useful here
return()
}
example()
isItADuck <- function(input){
test <- input == "duck"
return(test)
}
isItADuck = the name of the functioninput = the only argument for this function{} is the body of the functionreturn() to specify what gets returned when we call the function (in this case it will be TRUE or FALSE, because we are returning the result of a logical test)isItADuck <- function(input){
test <- input == "duck"
return(test)
}
the names input and test do not exist outside the function (i.e. after running the above code, you will get the following error if you type input into the R interpreter) Error in eval(expr, envir, enclos) : object 'input' not found
Nothing happens when we create the function. Stuff happens later when we call the function with specific arguments.
isItADuck <- function(input){
test <- input == "duck"
return(test)
}
I assume you ran the code above in R (i.e. you defined our function)
Now we can call the function with a specified value for our argument.
isItADuck("cat")
## [1] FALSE
isItADuck("cat")
## [1] FALSE
When we ask isItADuck() to run, it needs an argument called input. But remember, this value this doesn’t exist outside the function.
We solved this problem by providing "cat" as the value of input.
isItADuck("cat")
## [1] FALSE
Our function took an argument, determined whether or not it was a duck, and returned either TRUE or FALSE
Now we can re-use this function over and over
animals <- c("cat", "dog", "duck", "chicken")
for(animal in animals){
print(isItADuck(animal))
}
## [1] FALSE ## [1] FALSE ## [1] TRUE ## [1] FALSE
makeSound <- function(sound) {
#don't forget to install the beepr package
library(beepr)
beep(sound)
return(paste("I beeped sound number", sound))
}
makeSound(5)
x <- makeSound(7)
x
for(i in 1:11) {
makeSound(i)
Sys.sleep(1)
}