R - Lecture 7
R - Lecture 7
Ivan Belik
• function’s name
• sequence of statements
a <- c(1,2,3) 3
R: Functions
• We can create our own functions in R
• function’s name
• sequence of statements
• 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
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,
• 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
RESULT:
• 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
• However, paste(), compared to cat(), returns the concatenated values in a string format
• Remember:
Note:
• The code implies 3 interactive inputs. To make your code running correctly:
• Second, run the following three lines one by one providing the required interactive input
Note:
• Dividing a long program into functions allows you to debug the parts one at a time
• and then assemble them into a working whole.