This exercise will guide you through how to write your own R functions and how to use it.
After each assignment there is a hidden code chunk, containing clues for how to solve the problem. Start by trying on your own. If you are stuck, click on the “code” button.
We will now start by writing our very first function, and then executing it.
CONTINUE TO ADVANCED EXCERCISE 2
Create function
Hint:
# Remember the basic syntax for designing a function?
# If not, repeat this:
name_of_function <- function() {
}
Solution:
helloR <- function() {
print("Hello World")
}
Execute function
solution:
helloR()
Hint:
# Remember where we shoud put the input?
name_of_function <- function(input) {
}
Hint:
# Ahaaa, how to combine Hello and XXX?
# Perhaps this will give you a clue:
name <- "Andreas"
print(paste("Hello", name))
Solution:
#Define function
helloR <- function(name) {
print(paste("Hello", name))
}
# Execute function
helloR("Andreas")
helloR("Malie")
Hint:
# Remember how to define default inputs, no?
name_of_function <- function(input=Default) {
}
Solution:
#Define function
helloR <- function(name="Andreas") {
print(paste("Hello", name))
}
# Execute function - try some different options:
helloR()
helloR("Andreas")
helloR("Malie")
Nice! We are done!
Now lets see if any of your mates need help - and the presentation will continue shortly!
Usually, we dont want R to just print things to the screen. We usually want to store the output as a new variable, that we can later use for other calculations.
Hint 1:
# Lets repeat the syntax:
function_name <- function(input=default) {
output <- "make something out of input"
return(output)
}
Hint 2:
# What should we do with the input?
normalized <- iris$Sepal.Length / mean(iris$Sepal.Length)
Solution:
#Now, just put it together:
normalizeR <- function(inputvector) {
normalized <- inputvector/mean(inputvector)
return(normalized)
}
# Lets try the function out:
normalizeR(iris$Sepal.Length)
# Thets compare the output
boxplot(iris$Sepal.Length)
boxplot(normalizeR(iris$Sepal.Length))
Hint 1:
# The stop function
stop("Write an error message here")
Hint 2:
# Do you remember the ifelse statements?
if (class(iris$Sepal.Length) != "numeric") {
"Take some action"
}
Solution:
#Pay attention to the use of the braces and indentations:
normalizeR <- function(inputvector) {
if (class(inputvector) != "numeric") {
stop("Input is not a numeric vector")
}
normalized <- inputvector/mean(inputvector)
return(normalized)
}
# Try your function:
normalizeR(iris$Sepal.Length)
normalizeR("Johansson")
Have you not always been annoyed by the default black color in Rs plot functions? Soo boring! Lets hot it up. Create a function that per default plots anything in red colors. Call the function redplot
Hint:
#This is how a plot would look like:
plot(x=iris$Sepal.Length, y=iris$Sepal.Width, col="red")
Solution:
redplot <- function(x, y, col="red") {
plot(x=x, y=y, col=col)
}
But hey! What if the user wants to add i.e. a title on the x-axis? Leave roome in the formula for other arguments in the plot function:
Solution:
redplot <- function(x, y, col="red", ...) {
plot(x=x, y=y, col=col, ...)
}
# Ore make it eaven nicer:
redplot <- function(..., col="red") {
plot(..., col=col)
}
# Try it out
redplot(x=iris$Sepal.Length, y=iris$Sepal.Width)
redplot(x=iris$Sepal.Length, y=iris$Sepal.Width, xlab="Sepal Length", ylab="Sepal Width")
Its quite marvelous, is it not? See if you can use your function for other purposes.
These packages were used during this session:
sessionInfo()
## R version 3.5.1 (2018-07-02)
## Platform: x86_64-pc-linux-gnu (64-bit)
## Running under: Ubuntu 18.10
##
## Matrix products: default
## BLAS: /usr/lib/x86_64-linux-gnu/blas/libblas.so.3.8.0
## LAPACK: /usr/lib/x86_64-linux-gnu/lapack/liblapack.so.3.8.0
##
## locale:
## [1] LC_CTYPE=en_US.UTF-8 LC_NUMERIC=C
## [3] LC_TIME=sv_SE.UTF-8 LC_COLLATE=en_US.UTF-8
## [5] LC_MONETARY=sv_SE.UTF-8 LC_MESSAGES=en_US.UTF-8
## [7] LC_PAPER=sv_SE.UTF-8 LC_NAME=C
## [9] LC_ADDRESS=C LC_TELEPHONE=C
## [11] LC_MEASUREMENT=sv_SE.UTF-8 LC_IDENTIFICATION=C
##
## attached base packages:
## [1] stats graphics grDevices utils datasets methods base
##
## loaded via a namespace (and not attached):
## [1] compiler_3.5.1 backports_1.1.2 magrittr_1.5 rprojroot_1.3-2
## [5] tools_3.5.1 htmltools_0.3.6 yaml_2.2.0 Rcpp_1.0.0
## [9] stringi_1.2.4 rmarkdown_1.10 knitr_1.20 stringr_1.3.1
## [13] digest_0.6.18 evaluate_0.12