30

Statistical Programming with Rsite.iugaza.edu.ps/biqelan/files/2019/10/05R-Simple-Programming.pdf · Functions One of the great strengths of R is the user's ability to add functions

  • Upload
    others

  • View
    1

  • Download
    0

Embed Size (px)

Citation preview

Page 1: Statistical Programming with Rsite.iugaza.edu.ps/biqelan/files/2019/10/05R-Simple-Programming.pdf · Functions One of the great strengths of R is the user's ability to add functions

Statistical Programming with RLecture 5: Simple Programming

Bisher M. [email protected]

Department of Mathematics, Faculty of Science,

The Islamic University of Gaza

2019-2020, Semester 1

Page 2: Statistical Programming with Rsite.iugaza.edu.ps/biqelan/files/2019/10/05R-Simple-Programming.pdf · Functions One of the great strengths of R is the user's ability to add functions

Functions

One of the great strengths of R is the user's ability to add functions. Infact, many of the functions in R are actually functions of functions. Thecharacteristics of a function are given below.

� All computations in R are carried out by calling functions.

� A call to an R function takes zero or more arguments and returns asingle value.

� De�ning functions provides users a way of adding new functionality toR.

� Functions de�ned by users have the same status as the functions builtinto R.

Bisher M. Iqelan (IUG) Lecture 5: Simple Programming 1st Semester 2019 1 / 28

Page 3: Statistical Programming with Rsite.iugaza.edu.ps/biqelan/files/2019/10/05R-Simple-Programming.pdf · Functions One of the great strengths of R is the user's ability to add functions

De�ning a function

An R function() is created by using the keyword function. The basicsyntax of an R function de�nition is as follows

The syntax of an R function

function_name <- function(arg_1, arg_2, ...){

Function body

. . . ,

. . . ,...

. . . ,return(object)

}

Bisher M. Iqelan (IUG) Lecture 5: Simple Programming 1st Semester 2019 2 / 28

Page 4: Statistical Programming with Rsite.iugaza.edu.ps/biqelan/files/2019/10/05R-Simple-Programming.pdf · Functions One of the great strengths of R is the user's ability to add functions

Function Components

The di�erent parts of a function are:

� Function Name This is the actual name of the function. It is storedin R environment as an object with this name.

� Arguments An argument is a placeholder. When a function isinvoked, you pass a value to the argument. Arguments are optional;that is, a function may contain no arguments. Also arguments canhave default values.

� Function Body The function body contains a collection ofstatements that de�nes what the function does.

� Return Value The return value of a function is the last expression inthe function body to be evaluated.

Bisher M. Iqelan (IUG) Lecture 5: Simple Programming 1st Semester 2019 3 / 28

Page 5: Statistical Programming with Rsite.iugaza.edu.ps/biqelan/files/2019/10/05R-Simple-Programming.pdf · Functions One of the great strengths of R is the user's ability to add functions

Built-in Function

R has many in-built functions which can be directly called in the programwithout de�ning them �rst. We can also create and use our own functionsreferred as user de�ned functions. Simple examples of in-built functions are

seq(), mean(), max(), sum(x) and paste(...) etc. They are directlycalled by user written programs. You can refer most widely used R

functions.

Bisher M. Iqelan (IUG) Lecture 5: Simple Programming 1st Semester 2019 4 / 28

Page 6: Statistical Programming with Rsite.iugaza.edu.ps/biqelan/files/2019/10/05R-Simple-Programming.pdf · Functions One of the great strengths of R is the user's ability to add functions

User-de�ned Function: Creating and Calling

We can create our own-de�ned functions in R. They are speci�c to whatyou wants and once created they can be used like the built-in functions.Below is an example of how a function is created and used.

# Create a function with name# newFun to print squares# of numbers in sequence.

newFun <- function(a) {

for(i in 1:a) {

b <- i^2

print(b)

}

}

# Call the function newFun

# providing 8 as an argument.

> newFun(8)

[1] 1

[1] 4

[1] 9

[1] 16

[1] 25

[1] 36

[1] 49

[1] 64

Bisher M. Iqelan (IUG) Lecture 5: Simple Programming 1st Semester 2019 5 / 28

Page 7: Statistical Programming with Rsite.iugaza.edu.ps/biqelan/files/2019/10/05R-Simple-Programming.pdf · Functions One of the great strengths of R is the user's ability to add functions

Writing Function (empty arguments)

# Create a function without# an argument.

newFun1 <- function() {

for(i in 1:8) {

print(i^2)

}

}

# Call the function without providing# an argument.

> newFun1()[1] 1

[1] 4

[1] 9

[1] 16

[1] 25

[1] 36

[1] 49

[1] 64

Bisher M. Iqelan (IUG) Lecture 5: Simple Programming 1st Semester 2019 6 / 28

Page 8: Statistical Programming with Rsite.iugaza.edu.ps/biqelan/files/2019/10/05R-Simple-Programming.pdf · Functions One of the great strengths of R is the user's ability to add functions

Writing Function (empty arguments): More Examples

> 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 1st Semester 2019 7 / 28

Page 9: Statistical Programming with Rsite.iugaza.edu.ps/biqelan/files/2019/10/05R-Simple-Programming.pdf · Functions One of the great strengths of R is the user's ability to add functions

Writing Function (Empty Arguments Continue..)

Consider the following very simple example. Here, the arguments are empty

myvalue <- 1

myFun2 <- function() {

myvalue <- 5

print(myvalue)

}

> myFun2() > myvalue

[1] 5 [1] 1

myFun3 <- function() {

print(myvalue)

}

> myFun3()

[1] 1

Bisher M. Iqelan (IUG) Lecture 5: Simple Programming 1st Semester 2019 8 / 28

Page 10: Statistical Programming with Rsite.iugaza.edu.ps/biqelan/files/2019/10/05R-Simple-Programming.pdf · Functions One of the great strengths of R is the user's ability to add functions

Function with Several Arguments (by position and by name)

The arguments to a function call can be provided in the same sequence asde�ned in the function or they can be provided in a di�erent sequence butassigned to the names of the arguments.Suppose we want to create afunction with arguments x, y and z.

# Create a function with arguments.

newFun4 <- function(x,y,z) {

result <- x * y + z

print(result)

}

# Call the function by position of arguments.

> newFun4(5,3,11)[1] 26

# Call the function by names of the arguments.

> newFun4(x = 11, y = 5, z = 3)[1] 58

Bisher M. Iqelan (IUG) Lecture 5: Simple Programming 1st Semester 2019 9 / 28

Page 11: Statistical Programming with Rsite.iugaza.edu.ps/biqelan/files/2019/10/05R-Simple-Programming.pdf · Functions One of the great strengths of R is the user's ability to add functions

Calling a Function with Default Argument

We can de�ne the value of the arguments in the function de�nition and callthe function without providing any argument to get the default result. Butwe can also call such functions by providing new values of the argumentand get non default result.

# Create a function with arguments.

newFun5 <- function(x = 3, y = 6) {

result <- x * y

print(result)

}

# Call the function without giving any argument.

> newFun5()[1] 18

# Call the function with giving new values of the argument.

> newFun5(9,5)[1] 45

Bisher M. Iqelan (IUG) Lecture 5: Simple Programming 1st Semester 2019 10 / 28

Page 12: Statistical Programming with Rsite.iugaza.edu.ps/biqelan/files/2019/10/05R-Simple-Programming.pdf · Functions One of the great strengths of R is the user's ability to add functions

Matching Values to Arguments: Example

In this example, we create a display function to shows how R matchesvalues to arguments

dispFun <- function(x = 1, y = 2, z = 3) {

res <- c(x, y, z)

names(res) <- c("x", "y", "z") # This names each

return(res) # element of the vector

}

# no arguments # one argument # two arguments

> dispFun() > dispFun(55) > dispFun(55, 66)

x y z x y z x y z

1 2 3 55 2 3 55 66 3

# 2 arguments # 3 argument # only the value of z

> dispFun(55,,77) > dispFun(55,66,77) > dispFun(z=77)

x y z x y z x y z

55 2 77 55 66 77 1 2 77

Bisher M. Iqelan (IUG) Lecture 5: Simple Programming 1st Semester 2019 11 / 28

Page 13: Statistical Programming with Rsite.iugaza.edu.ps/biqelan/files/2019/10/05R-Simple-Programming.pdf · Functions One of the great strengths of R is the user's ability to add functions

In�x functions

Most functions in R are �pre�x� operators: the name of the function comesbefore the arguments. You can also create �in�x� functions where thefunction name comes in between its arguments, like + or -. Alluser-created in�x functions must start and end with %.For example, one could create a new operator that pastes togetherstrings:

> `%+%` <- function(x, y) paste(x, y)

# Use the function between the arguments

> "new" %+% " string"

[1] "new string"

# Use the function before the arguments

> `%+%`("new", " string")

[1] "new string"

Bisher M. Iqelan (IUG) Lecture 5: Simple Programming 1st Semester 2019 12 / 28

Page 14: Statistical Programming with Rsite.iugaza.edu.ps/biqelan/files/2019/10/05R-Simple-Programming.pdf · Functions One of the great strengths of R is the user's ability to add functions

In�x functions: More Examples

Following is an example of user-de�ned in�x operator to see if a number isexactly divisible by another.

"%Dv%" <- function(x,y){

if (x%%y ==0) return (TRUE)

else return (FALSE)

}

This function can be used as in�x operator x %Dv% y or as a function call"%Dv%"(x, y). Both are the same.

> 10 %Dv% 3 > 10 %Dv% 2 > "%Dv%"(10,5)

[1] FALSE [1] TRUE [1] TRUE

Bisher M. Iqelan (IUG) Lecture 5: Simple Programming 1st Semester 2019 13 / 28

Page 15: Statistical Programming with Rsite.iugaza.edu.ps/biqelan/files/2019/10/05R-Simple-Programming.pdf · Functions One of the great strengths of R is the user's ability to add functions

if Statement

Decision making is an important part of programming. This can beachieved in R programming using the conditional if...else statement.

R if statement

The syntax of if statement is:

if (test.expression) {statement

}

If the test.expression is TRUE, thestatement gets executed. But if it'sFALSE, nothing happens.

Flowchart of if statement

Example:

x <- 5if(x > 0){print("Positive number")}[1] "Positive number"

Bisher M. Iqelan (IUG) Lecture 5: Simple Programming 1st Semester 2019 14 / 28

Page 16: Statistical Programming with Rsite.iugaza.edu.ps/biqelan/files/2019/10/05R-Simple-Programming.pdf · Functions One of the great strengths of R is the user's ability to add functions

if...else Statement

R if. . . else statement

The syntax of if. . . else statement is:

if (test.expression) {statement1} else {statement2}

� The else part is optional and is onlyevaluated if test.expression is FALSE.� It is important to note that else must be inthe same line as the closing braces of the ifstatement.� Here, test.expression can be a logical ornumeric vector, but only the �rst element istaken into consideration.

Flowchart of if...else

statement

Bisher M. Iqelan (IUG) Lecture 5: Simple Programming 1st Semester 2019 15 / 28

Page 17: Statistical Programming with Rsite.iugaza.edu.ps/biqelan/files/2019/10/05R-Simple-Programming.pdf · Functions One of the great strengths of R is the user's ability to add functions

Example of if...else statement

Example 1:

a <- -5

if(a > 0){

print("Non-negative No.")

} else {

print("Negative No.")

}

[1] "Negative No."

if...else statement: Another way

The above conditional can also be written in a single line as follows.

if(a > 0) print("Non-negative No.") else print("Negative No.")

Bisher M. Iqelan (IUG) Lecture 5: Simple Programming 1st Semester 2019 16 / 28

Page 18: Statistical Programming with Rsite.iugaza.edu.ps/biqelan/files/2019/10/05R-Simple-Programming.pdf · Functions One of the great strengths of R is the user's ability to add functions

Example 2:

> a = -4

> if(a >= 0) 5 else 6

[1] 6

But, if the condition is a vector:

> a = c(-4,0,10)

> if(a >= 0) 5 else 6

[1] 6

Warning message:

In if (a >= 0) 5 else 6 :

the condition has length >1 and only the first element be used

Bisher M. Iqelan (IUG) Lecture 5: Simple Programming 1st Semester 2019 17 / 28

Page 19: Statistical Programming with Rsite.iugaza.edu.ps/biqelan/files/2019/10/05R-Simple-Programming.pdf · Functions One of the great strengths of R is the user's ability to add functions

Example 1

This example shows how we can use the for and the if functions to getthe sign of a numeric vector. In order to do the job for any di�erent vectorof values, we have to create a function.

> new.sign <- function(x)

{

for (i in 1:length(x)) {

if(x[i] > 0)

x[i] <- 1

else if(x[i] < 0)

x[i] <- -1 }

x

}

> new.sign(-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 1st Semester 2019 18 / 28

Page 20: Statistical Programming with Rsite.iugaza.edu.ps/biqelan/files/2019/10/05R-Simple-Programming.pdf · Functions One of the great strengths of R is the user's ability to add functions

ifelse statement

Most of the functions in R take vector as input and output a resultantvector. This vectorization of code, will be much faster than applying thesame function to each element of the vector individually.Similar to this concept, there is a vector equivalent form of the if. . . elsestatement in R, the ifelse() function.

Syntax of ifelse() function

ifelse(test.expression, x, y)

Here, test.expression must be a logical vector (or an object that can becoerced to logical). The return value is a vector with the same length astest.expression.This returned vector has element from x if the corresponding value oftest.expression is TRUE or from y if the corresponding value oftest.expression is FALSE. That is, the ith element of result will be x[i] iftest.expression[i] is TRUE else it will take the value of y[i].The vectors x and y are recycled whenever necessary.

Bisher M. Iqelan (IUG) Lecture 5: Simple Programming 1st Semester 2019 19 / 28

Page 21: Statistical Programming with Rsite.iugaza.edu.ps/biqelan/files/2019/10/05R-Simple-Programming.pdf · Functions One of the great strengths of R is the user's ability to add functions

Example 1 Continue...

Re-visit Example 1, one can do the job in a better way which avoidsiterations.

> sgnFun <- function(x){

ifelse(x > 0, 1, ifelse(x<0, -1, 0))

}

Now call the function to �nd the resultant vector of the input vector -10:5.

> sgnFun(-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 1st Semester 2019 20 / 28

Page 22: Statistical Programming with Rsite.iugaza.edu.ps/biqelan/files/2019/10/05R-Simple-Programming.pdf · Functions One of the great strengths of R is the user's ability to add functions

More Examples

Example 2: Consider the following function using if() function:

> 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 1st Semester 2019 21 / 28

Page 23: Statistical Programming with Rsite.iugaza.edu.ps/biqelan/files/2019/10/05R-Simple-Programming.pdf · Functions One of the great strengths of R is the user's ability to add functions

Example 2 Cont...

Re-visit Example 2 above and try to ease the job by using ifelse() functioninstead of if() function.

> ifFun2 <- function(x){

ifelse(x==2, "x=2", "x!=2")

}

> ifFun2(1)

[1] "x!=2"

> ifFun2(2)

[1] "x=2"

> ifFun2(rep(c(2,1),4))

[1] "x=2" "x!=2" "x=2" "x!=2" "x=2" "x!=2" "x=2" "x!=2"

Bisher M. Iqelan (IUG) Lecture 5: Simple Programming 1st Semester 2019 22 / 28

Page 24: Statistical Programming with Rsite.iugaza.edu.ps/biqelan/files/2019/10/05R-Simple-Programming.pdf · Functions One of the great strengths of R is the user's ability to add functions

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 1st Semester 2019 23 / 28

Page 25: Statistical Programming with Rsite.iugaza.edu.ps/biqelan/files/2019/10/05R-Simple-Programming.pdf · Functions One of the great strengths of R is the user's ability to add functions

A function returning a vector

Suppose we want to create a function which summarizes a numericalvariable in a few statistical terms (mean, variance etc) and returns a vectorwith 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 1st Semester 2019 24 / 28

Page 26: Statistical Programming with Rsite.iugaza.edu.ps/biqelan/files/2019/10/05R-Simple-Programming.pdf · Functions One of the great strengths of R is the user's ability to add functions

A function returning a vector Continue...

The output of this function is not directly readable (unless we investigatehow mysummary() was de�ned). A much more informative output can beobtained 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 1st Semester 2019 25 / 28

Page 27: Statistical Programming with Rsite.iugaza.edu.ps/biqelan/files/2019/10/05R-Simple-Programming.pdf · Functions One of the great strengths of R is the user's ability to add functions

A function returning a list

> 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] 25

Bisher M. Iqelan (IUG) Lecture 5: Simple Programming 1st Semester 2019 26 / 28

Page 28: Statistical Programming with Rsite.iugaza.edu.ps/biqelan/files/2019/10/05R-Simple-Programming.pdf · Functions One of the great strengths of R is the user's ability to add functions

Example: Multiple of a number

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 ofthe number 6.Try this function:

> multiple1=function(k){

y=k*(1:100)

y

}

Bisher M. Iqelan (IUG) Lecture 5: Simple Programming 1st Semester 2019 27 / 28

Page 29: Statistical Programming with Rsite.iugaza.edu.ps/biqelan/files/2019/10/05R-Simple-Programming.pdf · Functions One of the great strengths of R is the user's ability to add functions

Example: Tossing a coin

Write a function to simulate a coin toss which allows the user to set p, theprobability 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 1st Semester 2019 28 / 28

Page 30: Statistical Programming with Rsite.iugaza.edu.ps/biqelan/files/2019/10/05R-Simple-Programming.pdf · Functions One of the great strengths of R is the user's ability to add functions

End of lecture 5. Thank you.!!!