Return Multiple Objects from User-Defined Function in R (Example)

 

This tutorial illustrates how to return multiple outputs from a user-defined function in R.

The tutorial consists of the following content blocks:

Let’s get started…

 

Create User-Defined Function in R

First, we are creating our own manual function with several outputs, which we can use in the example of this R tutorial.

Consider the following R code:

my_fun <- function(x) {          # Create user-defined function
 
  y <- x + 1                     # Create two outputs within function
  z <- x + 2
 
  out <- list(y, z)              # Store output in list
  return(out)                    # Return output
}

As you can see based on our previous R syntax, we created the user-defined function my_fun, which is creating two outputs y and z.

The important part of this function is the list command. With the list command, we can return both outputs simultaneously.

In the following section, I’ll show you how this looks in practice. SO keep on reading.

 

Application of User-Defined Function

In this section, we’ll apply the manual function that we have created in the previous section. The following code stores the output of our function in the data object my_output:

my_output <- my_fun(5)           # Apply function

Now, we can print our data object my_output to the RStudio console:

my_output                        # Print two outputs to RStudio console
# [[1]]
# [1] 6
# 
# [[2]]
# [1] 7

As you can see based on the output of the RStudio console, we created a list output, which is containing our two values y and z.

 

Video, Further Resources & Summary

Have a look at the following video of my YouTube channel. In the video, I’m explaining the examples of this tutorial in R:

 

The YouTube video will be added soon.

 

Furthermore, you might want to have a look at some of the other tutorials of my website:

 

This tutorial showed how to extract more than one value from a manual function in the R programming language. In case you have further questions, don’t hesitate to let me know in the comments section.

 



Leave a Reply

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

Fill out this field
Fill out this field
Please enter a valid email address.

Menu
Top