The document explains how to create user-defined functions in R, allowing users to define specific functionalities similar to built-in functions. It provides examples of functions that print squares of numbers, functions without arguments, and functions that accept arguments both by position and by name. The document illustrates these concepts with code snippets demonstrating the creation and calling of these functions.
Download as PPTX, PDF, TXT or read online on Scribd
0 ratings0% found this document useful (0 votes)
2 views
Use Defined Functions
The document explains how to create user-defined functions in R, allowing users to define specific functionalities similar to built-in functions. It provides examples of functions that print squares of numbers, functions without arguments, and functions that accept arguments both by position and by name. The document illustrates these concepts with code snippets demonstrating the creation and calling of these functions.
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 3
User-defined Function
We can create user-defined functions in R. They are specific to
what a user wants and once created they can be used like the built-in functions. Below is an example of how a function is created and used.
# Create a function to print squares of numbers in sequence.
new.function <- function(a) { for(i in 1:a) { b <- i^2 print(b) [1] 1 } [1] 4 } [1] 9 [1] 16 # Call the function new.function supplying 6 as an argument. [1] 25 new.function(6) [1] 36 Calling a Function without an Argument
# Call the function without supplying an argument.
[1] 1 new.function() [1] 4 [1] 9 [1] 16 [1] 25 Calling a Function with Argument Values (by position and by name) The arguments to a function call can be supplied in the same sequence as defined in the function or they can be supplied in a different sequence but assigned to the names of the arguments.
# Create a function with arguments.
new.function <- function(a,b,c) { result <- a * b + c print(result) } [1] 26 [1] 58 # Call the function by position of arguments. new.function(5,3,11)