how to create a def in r

In R, to create a function, you can use the function keyword followed by the function's name and its arguments in parentheses. The code inside the function is enclosed in curly braces {}. Here's an example of how to create a function that returns the sum of two numbers:

main.r
my_sum <- function(x, y) {
  return(x + y)
}
45 chars
4 lines

In this example, my_sum is the name of the function, and x and y are the arguments that it expects. The function body simply returns the sum of x and y.

You can then call the function by passing it the required arguments:

main.r
result <- my_sum(2, 3)
print(result)
37 chars
3 lines

This will output 5, which is the result of calling the my_sum function with arguments 2 and 3.

related categories

gistlibby LogSnag