my_fun <- function(arguments) {
"body of code"
}6 Writing Functions
1 Writing own R functions
- Every R function has three parts:
- name
- a body of code
- a set of arguments
- The basic format of an R function
Functions are just another R object
Comas separate more than one argument
2 Example
- Write a function that calculates the area of a right triangle
. . .
calculate_right_triangle_area <- function(base, height) {
area <- 0.5 * base * height
return(area)
}. . .
- It takes two arguments:
baseandheight.
calculate_right_triangle_area(2, 3)[1] 3
3 Simulating rolling dice
The following codes simulate an experiment “rolling a dice”
sample(x = 1:6, size = 1)[1] 4
sample(x = 1:6, size = 1)[1] 4
Write a function roll() for the simulation
roll <- function() {
dice <- 1:6
out <- sample(x = dice, size = 1)
return(out)
}roll()has no arguments, and it will return a number between 1 to 6
- To use the function
roll(), first run the written R function codes in the R console. Then runroll()
# Start rolling dice
# roll 1
roll()[1] 1
# roll 2
roll()[1] 1
# See the function codes
rollfunction ()
{
dice <- 1:6
out <- sample(x = dice, size = 1)
return(out)
}
<bytecode: 0x7f9aaec56a60>
4 Functions with arguments
The number of heads in 10 fair coin toss
# Toss a fair coin 10 times
s10 <- sample(x = c(0,1), size = 10, replace = TRUE)
sum(s10)[1] 9
The number of heads in 20 fair coin toss
# Toss a fair coin 20 times
s20 <- sample(x = c(0,1), size = 20, replace = TRUE)
sum(s20)[1] 9
The number of heads in 100 fair coin toss
# Toss a fair coin 100 times
s100 <- sample(x = c(0,1), size = 100, replace = TRUE)
sum(s100)[1] 57
The
sizeargument ofsample()is changing for different number of coin tossCan you write a function in R that takes how many times to toss a fair coin and prints us how many times it lands on heads?
# Creating the function
toss_fair_coins <- function(times) {
out <- sample(x = 0:1, size = times, replace = T)
sum(out)
}Tossing coins 200/500 times
toss_fair_coins(times = 200)[1] 92
toss_fair_coins(times = 500)[1] 252
What will happen if you run the function without specifying the argument
toss_fair_coins()# Creating R function with default argument values
toss_fair_coins2 <- function(times = 100) {
out <- sample(x = 0:1, size = times, replace = T)
sum(out)
}Default value of an argument can be specified
E.g.,
times = 100will be considered iftimesis not supplied!
# No argument supplied
toss_fair_coins2()[1] 54
# If argument supplied
toss_fair_coins2(times=10000)[1] 5022
5 Exercise 6.1
Write an R function
roll_dice()that rolls a dicentimes (wherenis 1 or more) and returns the sum of the dice rolls.Write an R function
toss_bias_coins()that tosses a biased coinntimes (wherenis 1 or more times) and returns the number of heads. The probability of getting heads is 0.70.Write an R function that can simulate flipping a fair or biased coin. The probability of getting heads should not always be 0.70, but any value between 0 and 1!
6 Help for R functions
help("mean") or “?mean” to check the detail of mean()
help("mean") # equivalently ?mean
help.search("mean") #equivalently ??meanThe
help.search()function searches through the help documentation, code demonstrations and package vignettes and displays the results as clickable links for further explorationAnother useful function is
apropos()
apropos("mean") [1] ".colMeans" ".rowMeans" "colMeans" "kmeans"
[5] "mean" "mean.Date" "mean.default" "mean.difftime"
[9] "mean.POSIXct" "mean.POSIXlt" "rowMeans" "weighted.mean"
RStudio snippet can save your time. Type fun and wait some milliseconds to see suggestions (press Tab if they don’t appear). Select (or press Tab) on the snippet option to insert it. You can see and customize your snippets from Tools>Global Options>Code.