0% found this document useful (0 votes)
42 views20 pages

R - Lecture 7

Uploaded by

mxmlan21
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
42 views20 pages

R - Lecture 7

Uploaded by

mxmlan21
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 20

Lecture 7: Functions

Ivan Belik

Assembled and built based on:


https://openlibra.com/en/book/download/an-introduction-to-r-2
https://cran.r-project.org/doc/manuals/R-intro.pdf
http://www.programiz.com/r-programming/if-else-statement
http://www.programiz.com/r-programming/examples/odd-even
R: Functions
• Function is a named sequence of statements that performs a computation

• Any function has:

• function’s name
• sequence of statements

• In our codes, we can “call” the function by name

• Any function “takes” argument(s) and “returns” the result.

a <- c(1,2,3) 3
R: Functions
• We can create our own functions in R

• Defining a function, we specify:

• function’s name
• sequence of statements

• Defining a function, we specify:

• The formal structure of the function in R is the following:

Function_name <- function (argument) {


function’s statements
}

Note: function is the reserved word in R to create a function


R: Example
• We calculate the sum of three arguments: a, b, and c:

• To call the created function, we just call it by its name (my_function)


R: Function’s arguments
• we should be careful about arguments’ order

• But if we use named arguments (when we call the function) then the order does not matter:

The order is not the same as it is initially defined in the function's definition
R: Function arguments
• Also, we can mix named and unnamed arguments when we call a function:
R: Function arguments: default values
• We can make some arguments optional

• and use default values in case the user does not want to change them

• Results:
R: return statement
• The most useful thing is an opportunity to return specific variables for the further processing in the main block

• We assigned the returned value ( from my_function(a, b)) to s

• Next, updated s in the main block

• Finally, we printed s in the main block


R: return statement
• Functions can have multiple returns:

maximum <- function (x, y) { Results

if (x > y) {
return (x) }
else {

if (x == y) {
return (print("The numbers are equal"))
}
else {
return (y)
}
}
}
R: functions without return
• If you do not specify return in your function,

• Then R will return the last evaluated expression in the function

• Check the following example:

• RESULT:
R: local variables
• When we declare variables inside the function:

they are not related to any other variables with the same name outside the function:

RESULT:
R: Global variables
• If you want to declare a variable (in the function) that will be visible throughout the program

• Then you should use a global variable

• Superassignment operator <<- is used to assign a global variable

RESULT:

• When we assign a value to global x inside the function,


the update is reflected in the main block when we use the x
• When defining functions, avoid giving function arguments the same names as any variables that exist in the global R
environment (i.e., either variables defined outside of a function or variables defined using the superassignment
operator from inside the function)
Useful R operators and functions
R: operator infix
• Any standard operation in R is realized in the following way:

• But we can use infix operators for the given operations:

• We have to use back tick (`) to specify an infix operator


R: predefined infix operators
• Some built-in infix operators in R:

1. Reminder operator %% 2. Integer division %/% 3. Matching operator %in%


R: switch() function
• Another useful function is switch()

• switch() function notation:

switch ( statement, case1, case2, . . . )

• switch() evaluates the statement and returns one of the following cases (elements of the list)

• In the given example, switch() returns an item that correspond to the numeric value

• Also, statement can be a string:

• We will use switch() – function in the forthcoming example


Few more useful built-in functions
• paste() and cat() have a similar purpose: to concatenate

• However, paste(), compared to cat(), returns the concatenated values in a string format

• and cat() does not return anything

• Remember:

• print() function returns a value in R, but it does not make a concatenation:


Example
• “R Program to Make a Simple Calculator”*:

Note:

• The code implies 3 interactive inputs. To make your code running correctly:

• First, Select and run all lines till the line:

choice = as.integer(readline(prompt="Enter choice[1/2/3/4]: "))

• Second, run the following three lines one by one providing the required interactive input

• Third, run the rest of the code to see the results

Note:

• paste() and cat() have the similar purpose: to concatenate


• However, paste(), compared to cat(), returns value and cat() does not return anything

• So, let’s take look at the code

* Source code: http://www.programiz.com/r-programming/examples/simple-calculator


Example*
add <- function(x, y) { Result:
return(x + y)
} [1] "Select operation."
subtract <- function(x, y) { [1] "1.Add"
return(x - y) [1] "2.Subtract"
} [1] "3.Multiply"
multiply <- function(x, y) { [1] "4.Divide"
return(x * y) Enter choice[1/2/3/4]: 1
} Enter first number: 4
divide <- function(x, y) { Enter second number: 3
return(x / y) [1] "4 + 3 = 7"
}
# take input from the user
print("Select operation.")
print("1.Add")
print("2.Subtract")
print("3.Multiply")
print("4.Divide")

choice = as.integer(readline(prompt="Enter choice[1/2/3/4]: "))


num1 = as.integer(readline(prompt="Enter first number: "))
num2 = as.integer(readline(prompt="Enter second number: "))

operator <- switch(choice,"+","-","*","/")


result <- switch(choice, add(num1, num2), subtract(num1, num2), multiply(num1, num2), divide(num1, num2))

print(paste(num1, operator, num2, "=", result))


# cat(num1, operator, num2, "=", result) # alternative (to display results)
* Source code: http://www.programiz.com/r-programming/examples/simple-calculator
Why functions?
• It may not be clear why to divide a program into functions.
• There are several reasons:

• Creating a new function gives you an opportunity to name a group of statements


• It makes your program easier to read and debug

• Functions can make a program smaller by eliminating repetitive code


• Later, if you make a change, you only have to make it in one place

• Dividing a long program into functions allows you to debug the parts one at a time
• and then assemble them into a working whole.

• Well-designed functions are often useful for many programs


• Once you write and debug one, you can reuse it

You might also like