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:
- Create User-Defined Function in R
- Application of User-Defined Function
- Video, Further Resources & Summary
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:
Please accept YouTube cookies to play this video. By accepting you will be accessing content from YouTube, a service provided by an external third party.
If you accept this notice, your choice will be saved and the page will refresh.
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.
Statistics Globe Newsletter
4 Comments. Leave new
Thanks for this wonder full function with two output results. But can you please make it more attractive, if it can print out with the name of the outputs like your above example y=2, z=3
Hello Dr.Khurram,
Would you prefer something like this?
Regards,
Cansu
Thank you, Cansu for your kind reply!
You are welcome, I am glad that I could help.
Regards,
Cansu