4 C
London
Friday, December 20, 2024
HomeStatistics TutorialRHow to Return Value from Function in R (With Examples)

How to Return Value from Function in R (With Examples)

Related stories

Learn About Opening an Automobile Repair Shop in India

Starting a car repair shop is quite a good...

Unlocking the Power: Embracing the Benefits of Tax-Free Investing

  Unlocking the Power: Embracing the Benefits of Tax-Free Investing For...

Income Splitting in Canada for 2023

  Income Splitting in Canada for 2023 The federal government’s expanded...

Can I Deduct Home Office Expenses on my Tax Return 2023?

Can I Deduct Home Office Expenses on my Tax...

Canadian Tax – Personal Tax Deadline 2022

  Canadian Tax – Personal Tax Deadline 2022 Resources and Tools...

You can use the following methods to return one or more values from a function in R:

Method 1: Return One Value

my_function function(A, B) {
  C return(C)
}

Method 2: Return Multiple Values

my_function function(A, B) {
  C   return(list(C, D, E))
}

The following examples show how to use each method in practice.

Example 1: Return One Value from Function in R

The following code shows how to create a function that returns one value:

#define function that returns one value
multiply_values function(A, B) {
  C return(C)
}

#use function
multiply_values(10, 3)

[1] 30

Notice that the function returns one value: the product of 10 and 3.

Example 2: Return Multiple Values from Function in R

The following code shows how to create a function that returns multiple values:

math_stuff function(A, B) {
  C return(list(C, D, E))
}

#use function
math_stuff(10, 3)

[[1]]
[1] 30

[[2]]
[1] 13

[[3]]
[1] 7

The function returns three values:

  • The first value is 10 * 3 = 30
  • The second value is 10 + 3 = 13
  • The third value is 10 – 3 = 7

Note: In this particular example, we returned three values but you can use similar syntax to return as many values as you’d like using the return() argument.

Additional Resources

The following tutorials explain how to perform other common tasks in R:

How to Create a Nested For Loop in R
How to Loop Through Column Names in R
How to Append Values to a Vector Using a Loop in R

Subscribe

- Never miss a story with notifications

- Gain full access to our premium content

- Browse free from up to 5 devices at once

Latest stories