Make Object Created within Function Usable Outside in R (2 Examples)

 

This tutorial explains how to extract a data object created within a user-defined function in the R programming language.

The tutorial consists of this information:

Here’s the step-by-step process:

 

Example 1: Create User-Defined Function with Single Arrow

In this section, I’ll show how to create a manually defined function in R.

Have a look at the following R code:

my_fun1 <- function(x) {        # Create user-defined function
  out1 <- x^2
}

As you can see, we have created a user defined-function that takes an input value x. Within this function, the square of x is calculated and stored in the data object out1.

However, if we apply our function, the output cannot be extracted properly:

my_fun1(x = 5)                  # Apply user-defined function
out1                            # Try to get output of function
# Error: object 'out1' not found

After running our function, the data object out1 does not exist outside the function, even though we have defined it within the function. The error message “object not found” was returned to the RStudio console.

Next, I’ll explain how to resolve this problem!

 

Example 2: Create User-Defined Function with Double Arrow

Example 2 demonstrates how to create a user-defined function where the data object defined within the function is also usable outside the function.

For this, we have to use a double arrow (i.e. <<-) as assignment operator instead of a single arrow.

Have a look at the following R code:

my_fun2 <- function(x) {        # Create user-defined function
  out2 <<- x^2
}

Next, we can apply this function to a value of our choice:

my_fun2(x = 5)                  # Apply user-defined function
out2                            # Print output of function
# [1] 25

As you can see, the data object out2 contains the result of our function, and we can use this data object outside the function!

 

Video, Further Resources & Summary

Do you need more explanations on the contents of this article? Then I recommend watching the following video on my YouTube channel. In the video, I demonstrate the examples of this article.

 

 

Furthermore, you may want to read the related tutorials on my website:

 

To summarize: This tutorial has illustrated how to return an object created within a user-defined function in the R programming language. In case you have any further comments or questions, don’t hesitate to let me know in the comments.

 

Subscribe to the Statistics Globe Newsletter

Get regular updates on the latest tutorials, offers & news at Statistics Globe.
I hate spam & you may opt out anytime: Privacy Policy.


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.

Top