Function in R - r - learn r - r programming
- Functions are used to logically break our code into simpler parts which become easy to maintain and understand.
- It's pretty straightforward to create your own function in R programming.
- Here, we can see that the reserved word function is used to declare a function in R.
- The statements within the curly braces form the body of the function.
- These braces are optional if the body contains only a single expression.
- Finally, this function object is given a name by assigning it to a variable, func_name.
Sample Functions in C
How to call a function ?
- We can call the above function as follows.
- Here, the arguments used in the function declaration (x and y) are called formal arguments and those used while calling the function are called actual arguments.
Read AlsoApply functions on several call
- In the above function calls, the argument matching of formal argument to the actual arguments takes place in positional order.
- This means that, in the call pow(8,2), the formal arguments x and y are assigned 8 and 2 respectively.
- We can also call the function using named arguments.
- When calling a function in this way, the order of the actual arguments doesn't matter.
- For example, all of the function calls given below are equivalent.
- Furthermore, we can use named and unnamed arguments in a single call.
- In such case, all the named arguments are matched first and then the remaining unnamed arguments are matched in a positional order.
- In all the examples above, x gets the value 8 and y gets the value 2.
Default Values for Arguments
- We can assign default values to arguments in a function in R.
- This is done by providing an appropriate value to the formal argument in the function declaration.
- Here is the above function with a default value for y.
- The use of default value to an argument makes it optional when calling the function.
- Here, y is optional and will take the value 2 when not provided.