Sie sind auf Seite 1von 5

ST 104-Statistics Applications II - 2011/2012

R Functions

The ability to read, understand, modify and write simple pieces of code is an essential skill for modern data analysis One of the great strengths of R is the user's ability to add functions In fact, many of the functions in R are actually functions of functions A function in R, like a mathematical function, takes zero or more inputs, also called arguments, and returns an output The output is arrived at by going through a series of calculations, based on the input, which we specify in the body of the function The structure of a function is given below Syntax to define functions my.function <- function(argument.1, argument.2, ...) { body of the function return(the.return.value) } Syntax to call functions my.function(argument.1.value, argument.2.value, ...)

Example 1 square <- function(number) { answer <- number * number return(answer) } Here, square function number name of the function R function that creates functions parameter (name of the value) passed to the square function

{ } return

delimits the beginning of the function delimits the end of the function R function that specifies what the function returns, in this example, the value of answer

How to Write Functions in R Open a text editor Write an R function For this exercise, were going to put in some errors in our function Color coding is as follows: red for what the user types; blue for response by R: square <- function(number) { answer <- number * nmber return(answer } Save the file (by convention with an .R extension) Ex: example1.R Start R Use the function source to load your function into your R workspace: > source(example1.R) Note that the file name is in quotes and should include either the absolute path, or the path relative to the location of your R workspace R will indicate any syntax errors at this point and the line number where they are located

Ex: Error in source("example1.R") : example.R:5:1: unexpected '}' 4: return(answer 5: } ^ Go back to your text editor and fix the error(s), resave the file, and reread (source) the function in R

When you get a prompt after sourcing your file, then you can try using the function: > square(5) At this point, you may get a runtime error Ex: Error in square(5) : Object "nmber" not found Once again, go back to your text editor and fix the error(s), resave the file, and reread (source) the function in R Finally, after correcting all these errors, your function runs properly: Ex: > square(5) [1] 25 Example 2 myfct <- function(x1,x2=5) { z1 <- x1+x2 z2 <- x1/x2 z2=round(z2,2) myvec <- c(z1,z2) return(myvec) } When calling the function, myfct prints definition of function myfct(x2=2,x1=3) myfct(3,2) applies function to values 2 and 3 the argument names are not necessary, but then the order of the specified values becomes important does the same as before, but the default value '5' is used in this case

myfct(x1=2) Control structures

1. Conditional executions If statement Comparison operators: == : equal

!= : not equal >= : greater than or equal <= : less than or equal Logical operators: & : and | : or ! : not Syntax : if (condition) { statements } else { statements } Example a<-function(x) { if (any (x<0)) stop("Negative values") else cat("square root is:",sqrt(x)) } 2. Loops The most commonly used loop structures in R are 'for and 'while' loops For Loop flexible, but slow when looping over large number of fields (e.g. thousands of rows or columns)

Syntax : for(variable in sequence) { statements } Example

variance<-function(x) { i=0 d=0 for (i in 1:length(x)) { d=d+(((x[i]-mean(x))^2)/(length(x)-1)) } return(d) } While Loop similar to for loop, but the iterations are controlled by a conditional statement

Syntax : while(condition) { statements } Loop continues until condition returns FALSE

Example z <- 0 while(z<10) { z <- z+2 print(z) }

Das könnte Ihnen auch gefallen