R Functions

  • A block of code that is reusable
  • They are designed to perform specific tasks or set of tasks
  • Data or parameters can be passed through functions

How to Create Functions

Use the function() keyword to create functions

  1. add_numbers is the name of the function being defined.
  2. function(x, y) indicates that the function takes two parameters, x and y.
  3. { and } enclose the body of the function, which contains the code to be executed when the function is called.
  4. result <- x + y performs the addition of the two parameters (x and y) and stores the result in a variable named result.
  5. return(result) specifies that the result of the addition should be returned as the output of the function. The return() statement is optional in R; if omitted, the result of the last evaluated expression in the function is automatically returned.

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top