Presentation is loading. Please wait.

Presentation is loading. Please wait.

Ch.5 Writing functions.

Similar presentations


Presentation on theme: "Ch.5 Writing functions."— Presentation transcript:

1 Ch.5 Writing functions

2 5.1 Introduction The general form of a function is given by:
functionname <- function(arg1, arg2,...) { Body of function: a collection of valid statements }

3 5.1 Introduction The following short function meank calculates the mean of a vector x by removing the kpercent smallest and the k percent largest elements of the vector. meank <- function(x,k=0.1){ xt <- quantile(x, c(k,1-k)) mean( x[ x > xt[1] & x < xt[2] ]) } test <- rnorm(100) meank(test) [1]

4 5.2.1 Required and optional arguments
5.2 Arguments and variables 5.2.1 Required and optional arguments When calling functions in R, the syntax of the function definition determines whether argument values are required or optional. With optional arguments, the specification of the arguments in the function header is: argname = defaultvalue

5 5.2.1 Required and optional arguments
5.2 Arguments and variables 5.2.1 Required and optional arguments The argument x is required but the argument k is optional, having the default value 2: However, we can specify a different value for k. power <- function(x, k=2){ x^k } power(5) [1] 25 power() Error in power() : argument "x" is missing, with no default power(5,3) [1] 125

6 5.2 Arguments and variables
5.2.2 The `...' argument For example, graphical parameters that are passed to plotting functions or numerical parameters that are passed to numerical routines. Suppose you write a small function to plot the sin function from zero to xup. plotsin <- function(xup = 2*pi, ...){ x <- seq(0, xup, l = 100) plot(x,sin(x), type = "l", ...) } plotsin(col="red")

7 5.2 Arguments and variables
5.2.3 Local variables In the next example an object x will be defined with value zero. Inside the function functionx, xis defined with value 3. Executing the function functionx will not affect the value of the global variable `x'. x <- 0 functionx <- function(){ x <- 3 } functionx() [1] 3 x [1] 0

8 5.2 Arguments and variables
5.2.3 Local variables The arguments of a function can be objects of any type, even functions! Consider the next example: test <- function(n, fun){ u <- runif(n) fun(u) } test(10,sin) [1]

9 5.2 Arguments and variables
5.2.4 Returning an object Often the purpose of a function is to do some calculations on input arguments and return the result. By default the last expression of the function will be returned. myf <- function(x,y){ z1 <- sin(x) z2 <- cos(y) z1+z2 } list(z1,z2)

10 5.2 Arguments and variables
5.2.4 Returning an object To exit a function before it reaches the last line, use the return function. Any code after the return statement inside a function will be ignored. For example: myf <- function(x,y){ z1 <- sin(x) z2 <- cos(y) if(z1 < 0){ return( list(z1,z2) )} else{ return( z1+z2) } }

11 5.2 Arguments and variables
5.2.5 The Scoping rules This is free variables inside a function and for functions defined inside a function. Let's look at the following example function. myf <- function(x){ y = 6 z = x + y + a1 a2 = 9 insidef = function(p){ tmp = p*a2 sin(tmp) } 2*insidef(z)

12 5.2 Arguments and variables
5.2.5 The Scoping rules R tries to find a1 in the environment where myf was created but there is no object a1 myf(8) Error in myf(8) : object "a1" not found define the objects a1 and a2 but what value did a2 in the function insidef get? a1 <- 10 a2 <- 1000 [1] It took a2 in myf, so a2 has the value 9

13 5.2 Arguments and variables
5.2.6 Lazy evaluation When writing functions in R, a function argument can be defined as an expression like: myf <- function(x, nc = length(x)){ x <- c(x, x) print(nc) } xin <- 1:10 myf(xin) [1] 20

14 5.3.1 Tests with if and switch
5.3 Control flow 5.3.1 Tests with if and switch The general form of the if construction has the form if(test){ ...true statements... } else { ...false statements... }

15 5.3.1 Tests with if and switch
5.3 Control flow 5.3.1 Tests with if and switch myplus <- function(x, y){ n1 <- length(x) n2 <- length(y) if(n1 > n2){ z <- x[1:n2] + y } else { z <- x + y[1:n1] } z } myplus(1:10, 1:3) [1] 2 4 6

16 5.3.1 Tests with if and switch
5.3 Control flow 5.3.1 Tests with if and switch The switch function has the following general form: Simple example is Choosing between two calculation methods. switch(object, "value1" = {expr1}, "value2" = {expr2}, {other expressions} ) mycalc <- function(x, method="ml"){ switch(method, "ml" = { my.mlmethod(x) }, "rml" = { my.rmlmethod(x) } }

17 5.3.2 Looping with for and while
5.3 Control flow 5.3.2 Looping with for and while The for, while and repeat constructions are designed to perfom loops in R. They have the following forms. for(i in for_object){ some expressions } while(condition){

18 5.3.2 Looping with for and while
5.3 Control flow 5.3.2 Looping with for and while In the for loop some expressions are evaluated for each element i in for object: Simple example is a recursive fillter. arsim <- function(x, phi){ for(i in 2:length(x)){ x[i] <- x[i] + phi*x[i-1] } x arsim(1:10, 0.75) [1] [6]

19 5.3.2 Looping with for and while
5.3 Control flow 5.3.2 Looping with for and while In the while loop some expressions are repeatedly executed until the logical condition is FALSE. Make sure that the condition is FALSE at some stage, otherwise the loop will go on indefinitely. mycalc <- function(){ tmp <- 0; n <- 0 while(tmp < 100){ tmp <- tmp + rbinom(1,10,0.5) n <- n +1 } cat("It took ") cat(n) cat(" iterations to finish \n")

20 5.4.1 The traceback function
5.4 Debugging your R functions 5.4.1 The traceback function The R language provide the user with some tools to track down unexpected behavior during the execution of (user written) functions. For example, A function may throw warnings at you. Although warnings do not stop the execution of a function and could be ignored, you should check out why a warning is produced. A function stops because of an error. Now you must really x the function if you want it to continue to run until the end.

21 5.4.1 The traceback function
5.4 Debugging your R functions 5.4.1 The traceback function Your function runs without warnings and errors, however the number it returns does not make any sense. The first thing you can do when an error occurs is to call the function traceback. It will list the functions that were called before the error occurred. Consider the following two functions.

22 5.4.1 The traceback function
5.4 Debugging your R functions 5.4.1 The traceback function myf <- function(z){ x <- log(z) if( x > 0){ print("PPP") } else { print("QQQ") testf <- function(pp) myf(pp)

23 5.4.1 The traceback function
5.4 Debugging your R functions 5.4.1 The traceback function Executing the command testf(-9) will result in an error, execute traceback to see the function calls before the error. Error in if (x > 0) { : missing value where TRUE/FALSE needed In addition: Warning message: NaNs produced in: log(x) traceback() 2: myf(pp) 1: testf(-9) options(warn = 2)

24 5.4.2 The warning and stop functions
5.4 Debugging your R functions 5.4.2 The warning and stop functions You, as the writer of a function, can also produce errors and warnings. In addition to putting ordinary print statements like print("Some message") in your function, you can use the function warning. For example, variation <- function(x) { if(min(x) <= 0) warning("variation only useful for positive data") } sd(x)/mean(x)

25 5.4.2 The warning and stop functions
5.4 Debugging your R functions 5.4.2 The warning and stop functions variation(rnorm(100)) [1] Warning message: variation only useful for positive data in: variation(rnorm(100))

26 5.4.2 The warning and stop functions
5.4 Debugging your R functions 5.4.2 The warning and stop functions If you want to raise an error you can use the function stop. In the above example when we replace warning by stop R would halt the execution. variation(rnorm(100)) Error in variation(rnorm(100)) : variation only useful for positive data

27 5.4.3 Stepping through a function
5.4 Debugging your R functions 5.4.3 Stepping through a function With traceback you will now in which function the error occurred, it will not tell you where in the function the error occurred. To find the error in the function you can use the function debug, which will tell R to execute the function in debug mode. If you want to step through everything you will need to set debug flag for the main function and the functions that the main function calls:

28 5.4.3 Stepping through a function
5.4 Debugging your R functions 5.4.3 Stepping through a function debug(testf) debug(myf) testf(-9) debugging in: testf(-9) debug: { myf(pp) } Browse[1]>

29 5.4.3 Stepping through a function
5.4 Debugging your R functions 5.4.3 Stepping through a function Now execute the function testf, R will display the body of the function and a browser environment is started. testf(-9) debugging in: testf(-9) debug: { myf(pp) } Browse[1]>

30 5.4 Debugging your R functions
5.4.4 The browser function It may happen that an error occurs at the end of a lengthy function. To avoid stepping through the function line by line manually, the function browser can be used. Inside your function insert the browser() statement at a location where you want to enter the debugging environment. myf <- function(x) { ... some code ... browser() }

31 Thank you ! “The quiet statisticians have changed our world
not by discovering new facts or technical developments but by changing the ways that we reason, experiment and form our opinions ... “ by Ian Hacking


Download ppt "Ch.5 Writing functions."

Similar presentations


Ads by Google