Statistical Programming with R Lecture 5: Simple Programming Bisher M. Iqelan biqelan@iugaza.edu.ps Department of Mathematics, Faculty of Science, The Islamic University of Gaza 2017-2018, Semester 1
Functions All computations in R are carried out by calling functions. A call to an R function takes zero or more arguments and returns a single value. Dening functions provides users a way of adding new functionality to R. Functions dened by users have the same status as the functions built into R. Bisher M. Iqelan (IUG) Lecture 5: Simple Programming 1 st Semester 2017 1 / 18
Dening a function A new function is dened / created by a construct of the form <- function( arglist ) expr where fun.name fun.name is a variable where we store the function. This variable will be used to call the function later arglist is a list of formal arguments. This list can be empty (in which case the function takes no arguments) can have just some names (in which case these names become variables inside the function, whose values have to be supplied when the function is called) can have some arguments in name = value form, in which case the names are variables available inside the function, and the values are their default values expr is an expression (typically an expression block), referred to as the body of a function (which can make use of the variables dened in the argument list). Inside functions, there can be a special return(val) call which exits the function and returns the value val Bisher M. Iqelan (IUG) Lecture 5: Simple Programming 1 st Semester 2017 2 / 18
Write an R function To understand the concept of writing a new function in R, consider the following very simple example. cube <- function(number) { result <- number * number * number # or number**3 return(result) cube is the name of the function. function is the R function that creates functions. number is the parameter (name of the value) passed to the cube function. { delimits the beginning of the function delimits the end of the function return is the R function that species what the function returns, in this example, the value of result Bisher M. Iqelan (IUG) Lecture 5: Simple Programming 1 st Semester 2017 3 / 18
Writing Function (empty arguments) > fn <- function(){ # A simple function without argument print("hello") > fn() [1] "hello" Another example: By default the value of the last line is returned. Here, we have a simple function with two objects. The last one is returned. > test <- function() { x <-1 z <- 2 > res <- test() > res [1] 2 Bisher M. Iqelan (IUG) Lecture 5: Simple Programming 1 st Semester 2017 4 / 18
Writing Function (Empty Arguments Continue..) Consider the following very simple example. Here, the arguments are empty > myvalue <- 1 > myfun1 <- function() { myvalue <- 5 print(myvalue) > myfun1() [1] 5 > myvalue [1] 1 > myfun2 <- function() { print(myvalue) > myfun2() [1] 1 Bisher M. Iqelan (IUG) Lecture 5: Simple Programming 1 st Semester 2017 5 / 18
Writing Function Continue... Let us dene a function which gives the standard deviation of a vector x. We can create this function as follows. > standard.deviation<- function(x){ sqrt(var(x)) > x <- rnorm(100, mean=0, sd=2) > var(x) [1] 3.494888 > standered.deviation(x) [1] 1.869462 > sd(x) [1] 1.869462 Bisher M. Iqelan (IUG) Lecture 5: Simple Programming 1 st Semester 2017 6 / 18
Function with several arguments Functions can take several arguments. Suppose we want to calculate x 2 + y 2 for inputs of x and y: > f <- function(x, y) { value <- x^2 + y^2 return(value) > f(x = 2, y = 3) [1] 13 It is a good practice to name the arguments (as we did above) when calling a function, but it is not necessary: > f(5, 0) [1] 25 Bisher M. Iqelan (IUG) Lecture 5: Simple Programming 1 st Semester 2017 7 / 18
Inx functions Most functions in R are prex operators: the name of the function comes before the arguments. You can also create inx functions where the function name comes in between its arguments, like + or -. All user-created inx functions must start and end with %. For example, one could create a new operator that pastes together strings: > `%+%` <- function(x, y) paste(x, y) > "new" %+% " string" [1] "new string" > `%+%`("new", " string") [1] "new string" Bisher M. Iqelan (IUG) Lecture 5: Simple Programming 1 st Semester 2017 8 / 18
Example 1 Hence, to obtain the standard.deviation notice that we used two existing functions, the sqrt() and var(). This is a fundamental idea when there is need for dening a new function in R. This example shows how we can use the for and the if function to get the sign of a real number. > new.sign <- function(x) { for (i in 1:length(x)) { x > new.sign(-10:5) if(x[i] > 0) x[i] <- 1 else if(x[i] < 0) x[i] <- -1 [1] -1-1 -1-1 -1-1 -1-1 -1-1 0 1 1 1 1 1 Bisher M. Iqelan (IUG) Lecture 5: Simple Programming 1 st Semester 2017 9 / 18
Example Continue... However a better way is the following which avoids iterations. > sgnfunction <- function(x) { ifelse(x > 0, 1, ifelse(x<0, -1, 0)) > sgnfunction(-10:5) [1] -1-1 -1-1 -1-1 -1-1 -1-1 0 1 1 1 1 1 Bisher M. Iqelan (IUG) Lecture 5: Simple Programming 1 st Semester 2017 10 / 18
Example 2 Consider the following function using if statement: > iffun=function(x){ if (x==2){ print ("x=2") else { print ("x!=2") > iffun(1) [1] "x!=2" > iffun(2) [1] [1] "x=2" Bisher M. Iqelan (IUG) Lecture 5: Simple Programming 1 st Semester 2017 11 / 18
Example 2 Cont... > iffun2=function(x){ ifelse(x==2, "x=2", "x!=2") > iffun2(1) [1] "x!=2" > iffun2(2) [1] [1] "x=2" Bisher M. Iqelan (IUG) Lecture 5: Simple Programming 1 st Semester 2017 12 / 18
args() and body() functions In R, args() and body() give the two components of a function: > args(new.sign) function (x) NULL > body(new.sign) { for (i in 1:length(x)) { if (x[i] > 0) x[i] <- 1 else if (x[i] < 0) x[i] <- -1 x Bisher M. Iqelan (IUG) Lecture 5: Simple Programming 1 st Semester 2017 13 / 18
A function returning a vector Suppose we want to create a function which summarizes a numerical variable in a few statistical terms (mean, variance etc) and returns a vector with these terms. This can be done with > mysummary <- function(x) { value <- c(mean(x), median(x), var(x), min(x), max(x)) return(value) > mysummary(-10:20) [1] 5.00000 5.00000 82.66667-10.00000 20.00000 Bisher M. Iqelan (IUG) Lecture 5: Simple Programming 1 st Semester 2017 14 / 18
A function returning a vector Continue... The output of this function is not directly readable (unless we investigate how mysummary was dened). A much more informative output can be obtained by naming the components of the output vector: > mysummary <- function(x) { value <- c(mean = mean(x), med = median(x), var = var(x),min = min(x), max = max(x)) return(value) > mysummary(-10:20) mean med var min max 5.00000 5.00000 82.66667-10.00000 20.00000 Bisher M. Iqelan (IUG) Lecture 5: Simple Programming 1 st Semester 2017 15 / 18
A function returning a list A function can also return a list. For example: > mysummary <- function(x) { value <- list(mean = mean(x), med = median(x), var = var(x), min = min(x), max = max(x)) return(value) > (v <- mysummary(cars$speed)) $mean [1] 15.4 $med [1] 15 $var [1] 27.95918 $min [1] 4 $max [1] Bisher M. 25Iqelan (IUG) Lecture 5: Simple Programming 1 st Semester 2017 16 / 18
Example: Multiple of a number Example, a vector x containing the rst 100 multiples of the number k. > multiple=function(k){ x=0 for(i in 1:100) { x[i]=k*i x # This last entry is the output from the function. # The function only outputs the last line. To run the programs, type multiple(6). This gives the rst 100 multiples of 6. Bisher M. Iqelan (IUG) Lecture 5: Simple Programming 1 st Semester 2017 17 / 18
Example: Tossing a coin Write a function to simulate a coin toss which allows the user to set p, the probability that the coin shows a head. coin=function(p) { u=runif(1) # Shorthand for U(0,1). if(u<=p) coin="head" if(u>p) coin="tail" coin # This is the output from the program. To run the programs, assuming a fair coin, type coin(0.5). Bisher M. Iqelan (IUG) Lecture 5: Simple Programming 1 st Semester 2017 18 / 18
End of lecture 5. Thank you.!!!