R Language: return

0

The `return` statement is a control structure in R that can be used to exit a function. The `return` statement can be used to return a value from a function, or to simply exit the function without returning a value.

The syntax for the `return` statement is as follows:

return(value)

where `value` is the value that you want to return from the function. If you do not specify a value for `value`, the `return` statement will simply exit the function without returning a value.

For example, the following code defines a function that takes two numbers as input and returns the sum of the two numbers:

function(x, y) {

  sum <- x + y

  return(sum)

}

This function can be used as follows:

result <- function(x, y) {

  sum <- x + y

  return(sum)

}


result(10, 20)

This code will return the value 30, which is the sum of the numbers 10 and 20.

The `return` statement can also be used to exit a function without returning a value. For example, the following code defines a function that checks if a number is even. If the number is even, the function returns the value `TRUE`. If the number is not even, the function exits without returning a value.

function(x) {

  if (x %% 2 == 0) {

    return(TRUE)

  }

}

This function can be used as follows:

is.even(10)

This code will return the value `TRUE`, because 10 is an even number.

The `return` statement is a powerful tool for controlling the flow of execution in functions. It can be used to return values from functions, or to simply exit functions without returning values.

Post a Comment

0Comments
Post a Comment (0)